Ricky Ricky - 1 year ago 66
MySQL Question

Retrieving Data from MySQL database based on PHP Variable

I have a challenge where when searching a MySQL database based on a pre defined PHP variable does not seem to work. The following is my basic PHP Code:

$servername = "localhost"
$username = "MYUSERNAME";
$password = "MYPASSWORD";
$dbname = "MYDBNAME";

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

$user = "rickys";
echo $user;

$sql = "SELECT id, uname, pass FROM table WHERE uname =".$user;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "Gained Access";
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$dusername = $row["uname"];
$dpassword = $row["pass"];

echo "Error";}?>

The following is the data in my MySQL Database:

| id | uname | pass |
| 123 | rickys | 12345|

I have figured out that it doesn't enter the while loop. I think it may be a problem with my variable

Answer Source

your sql is wrong

$sql = "SELECT id, uname, pass FROM table WHERE uname = '$user'";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download