Home » Php » php – how to connect to database from wordpress shortcode

php – how to connect to database from wordpress shortcode

Posted by: admin February 25, 2020 Leave a comment

Questions:

How would I make this database echo out these a tags. the code words on a seperate but wont work on the short code

function get_repair_prices(){
$servername = "localhost";
$username = "localseo_prices";
$password = "******";
$dbname = "localseo_getitfixed";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM repair_prices";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo "<a href=''>".$row['btn_name']."</a>";
    }
} else {
    echo "0 results";
}
$conn->close();

}
add_shortcode('price_shortcode', 'get_prices');

it works as a seperate php file but will not output the data as shortcode

How to&Answers:

Try this:

function get_repair_prices($atts){
    $servername = "localhost";
    $username = "localseo_prices";
    $password = "******";
    $dbname = "localseo_getitfixed";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM repair_prices";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
          echo "<a href=''>".$row['btn_name']."</a>";
        }
    } else {
        echo "0 results";
    }
    $conn->close();

}
add_shortcode('price_shortcode', 'get_repair_prices');