virtuon92 virtuon92 - 10 days ago 7
PHP Question

Simple Mysqli Select query

So im trying to to post some data from database in wordpress ,i conect to the database normaly but it wont get any data from it. I have no idea what am i doing wrong.Here is the code

<?php
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "MyDB";

$conn = new mysqli($servername, $username, $password);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully"."</br>";

$sql = "SELECT event_name FROM wp_em_events";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Name :".$row["event_name"];
}
} else {
echo "0 results";
}

$conn->close();
?>

Answer

You're missing the database name from your connection. Change this:

$conn = new mysqli($servername, $username, $password);

to

$conn = new mysqli($servername, $username, $password, $dbname);