'How do I run an sql query in php?
When I try and run my query it turns out blank (not NULL, just not printing a value). If I run my query in my database it returns the value Im looking for.
When I run my code it notifies me the connection was successful. (I didnt include my db variable info to protect the sensitive info but it is correct)
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "error";
}
else{
echo "conn successful";
}
$sql = "SELECT app_ref_person_submitted_by
FROM vacancy_applications
WHERE app_ref_vacancy = 306";
$result = $conn->query($sql);
echo $result;
$conn-> close();
Solution 1:[1]
Try below code,
<?php
$conn = new mysqli('localhost', 'jaydeep_mor', 'jaydeep_mor', 'jaydeep_mor');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "error";
}
else{
echo "conn successful";
}
$sql = "SELECT app_ref_person_submitted_by
FROM vacancy_applications
WHERE app_ref_vacancy = 306";
$result = $conn->query($sql);
while($row = $result->fetch_array()){
echo $row['app_ref_person_submitted_by'];
}
$conn-> close();
?>
Solution 2:[2]
This will help you to solve the problem.
$sql = "SELECT app_ref_person_submitted_by FROM vacancy_applications
WHERE app_ref_vacancy = 306";
$result = $conn->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
echo $row['app_ref_person_submitted_by'];
}
}
$conn-> close();
Solution 3:[3]
You should fetch the rows before you display them.
while($row = $result->fetch_assoc())
print_r($row);
You can use $row['field'] to reference to a specific field in the database.
Solution 4:[4]
if ($result) {
while ($row = $result->fetch_array($result)) {
echo $row['app_ref_person_submitted_by'];
}
}
Solution 5:[5]
You cannot just print the $result. Try this,
while ( $rows = $result->fetch_assoc() ){
print_r($rows);
//echo $rows['field'];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jaydeep Mor |
| Solution 2 | Kasun Dinesh Madusanke |
| Solution 3 | Horu Cardona |
| Solution 4 | harsh kumar |
| Solution 5 |
