I am new to PHP.
I am trying to display the details of employees in form of table.
But while($row = $result->fetchObject()) part is not executing, as $result->fetchObject() is returning false. Has it something to do with $rows = $result->fetchAll();?
Here's the code snippet.
$sql = "SELECT id, name, designation FROM employees";
if ($result = $pdo->query($sql)) {
$rows = $result->fetchAll();
$num_rows = count($rows);
if ($num_rows > 0) {
echo "<table>\n";
echo " <tr class=\"heading\">\n";
echo " <td>ID</td>\n";
echo " <td>Name</td>\n";
echo " <td>Designation</td>\n";
echo " </tr>\n";
while($row = $result->fetchObject()) {
echo " <tr>\n";
echo " <td>" . $row->id . "</td>\n";
echo " <td>" . $row->name . "</td>\n";
echo " <td>" . $row->designation . "</td>\n";
echo " </tr>\n";
}
echo "</table>";
} else {
echo "No employees in database.";
}
else {
echo "ERROR: Could not execute $sql. " . print_r
($pdo->errorInfo());
}
PDO's documentation is a little confusing on this, but the PDOStatement::fetch() method and its cousin fetchAll() return false when no more rows are available to return. The docs say it returns false on failure, and a lack of available rows counts as a failure.
Your initial call to fetchAll() gets all the rows from the PDOstatement result object and there are no more for the fetchObject() call to retrieve so it returns false.
You only need your initial call to fetchAll(), but you may need to set its fetch type to PDO::FETCH_OBJ if you did not previously set the default fetch type for your connection.
Then, you can replace your while loop with a simple foreach loop over the $rows array you already have. This has the added benefit of separating your display logic from your database query business logic a little more:
if ($result = $pdo->query($sql)) {
// Fetch them now, as objects
$rows = $result->fetchAll(PDO::FETCH_OBJ);
$num_rows = count($rows);
if ($num_rows > 0) {
echo "<table>\n";
echo " <tr class=\"heading\">\n";
echo " <td>ID</td>\n";
echo " <td>Name</td>\n";
echo " <td>Designation</td>\n";
echo " </tr>\n";
// $rows now has everything you need, just loop over it
foreach ($rows as $row {
echo " <tr>\n";
echo " <td>" . htmlspecialchars($row->id) . "</td>\n";
echo " <td>" . htmlspecialchars($row->name) . "</td>\n";
echo " <td>" . htmlspecialchars($row->designation) . "</td>\n";
echo " </tr>\n";
}
echo "</table>";
} else {
echo "No employees in database.";
}
else {
echo "ERROR: Could not execute $sql. " . print_r
($pdo->errorInfo());
}
Note also, that I added calls to htmlspecialchars() while writing output to HTML. That is always recommended, so that characters like < > & which have special meaning in HTML are properly encoded, and avoids cross-site scripting vulnerabilities if those values originated as user input.
Related
I am trying to learn about PDO and while i am trying to return some values from database i keep getting false as return from my var_dump($row) and i can't figure out why.
This is my code
require("db.php");
$stmt = $db->query("SELECT * FROM names");
while($row = $stmt->fetch(PDO::FETCH_ASSOC));
{
echo $row['name'] . " " . $row['surname'] . "<br>";
var_dump($row);
}
The weird part is that when I do it like this it returns desired database records.
foreach($db->query("SELECT * FROM names") as $row){
echo $row['name'] . " " . $row['surname'] . "<br>";
}
Note: Yes i know i should be using prepared statements,but i haven't got to that part yet.
It's basically a typo caused by
// ↓this
while($row = $stmt->fetch(PDO::FETCH_ASSOC));
{
echo $row['name'] . " " . $row['surname'] . "<br>";
var_dump($row);
}
The semicolon before the brace disassociates the loop from the code in the braces, and it runs through the result set without doing anything.
You end up with false when you var_dump($row) because you've already fetched the last row, then the next fetch returns false.
I have this PHP code, which fetches data from my SQL database called "comments".
This code prints out every comment in the table:
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
}
echo '<div class = "white_line_comments"></div>';
} else {
echo "0 results";
}
This has worked fine so far, everything prints as it's supposed to.
Then I decided I wanted a way to give each individual comment some sort of identification to make them unique. I tried putting each single comment into its own div, using the SQLtable row id as id for the div.
However, when I try to access my webpage now, it tells me the website doesn't work (HTTP Error 500).
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='$row[' id'].'>";
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
echo '</div>';
}
echo '
<div class="white_line_comments"></div>';
} else {
echo "0 results";
}
Any ideas on this? I guess I must've done something wrong when including the div, but I can't figure out what!
You have an error in this line after starting while loop:
echo "<div class ='$row['id'].'>";
It should be
echo "<div class ='". $row['id'] ."'>";
You should also configure your web server/hosting/localhost to throw a PHP error.
Read this if you are on localhost or your own server:
How can I make PHP display the error instead of giving me 500 Internal Server Error
Read this if you are using shared hosting: How do I displaying details of a PHP internal server error?
echo "<div class ='$row['id'].'>";
First line in while loop should look like this
echo "<div class = '".$row['id']."'>";
or
echo "<div class = '$row['id']'>"
You have mixed different apostrophe, try this:
echo "<div class ='" . $row['id'] . "'>";
I have a chemical database where users can search for items. If I search for a test item such as "heroin" (which exists as a test row in my database), I get no results returned, however if the search is for "her", then the appropriate results are generated.
When I run the SQL script in the database (Navicat mysql), then I get the correct result, so I believe the problem is with my PHP code. (Yes, I understand that I should upgrade to PDO structures, but that doesn't solve the current problem.)
My PHP script has a search field returning $item.
When $item is only a partial match, I get expected results, however, when $item is the same as the entire string, there are no matches returned.
$item = $_POST['item'];
$log_data = 'Searched for ' . $item;
$user_name = $user_data['username'];
user_log($user_name, $log_data);
$item=trim($item);
if($item !== ""){
$count = 0;
$chem = mysql_query("SELECT *
FROM Chemicals
WHERE Chemicals.Name_Chem1 LIKE '%{$item}%'
ORDER BY Chemicals.Name_Chem1 ASC");
while ($row = mysql_fetch_array($chem)) {
echo "<table border='0'>
<tr class='content'>
<th>CAS</th>
<th>Name</th>
<th>IUPAC Name</th>
<th>Common Name</th>
<th>German Chemical</th>
<th>German Common</th>
</tr>";
while ($row = mysql_fetch_array($chem)) {
$count ++;
echo "<tr>";
echo "<td class='content'>" . $row['CAS'] . "</td>";
echo "<td class='content'>" . "<a href='item_result.php?CAS="
. $row['CAS'] . "'>" . $row['Name_Chem1'] . "</a>" . "</td>";
echo "<td class='content'>" . $row['Name_IUPAC'] . "</td>";
echo "<td class='content'>" . $row['Name_Common'] . "</td>";
echo "<td class='content'>" . $row['Name_German_Chemical'] . "</td>";
echo "<td class='content'>" . $row['Name_German_Common'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
echo "There are ", $count, "results.";
}
The query works fine in MySQL, but not in the PHP script.
Here is the problem. Your fetch code is structured like this:
while ($row = mysql_fetch_array($chem)) {
while ($row = mysql_fetch_array($chem)) {
// Do something
}
}
Each time you call the fetch function, it "consumes" a row and moves the internal result pointer by one. Thus, when you do a search for which you expect exactly one result, by the time the inner loop is run, you have already consumed the row in the outer loop.
The outer loop should be replaced with an if() that checks the result count instead.
For some reason this is returning everything from the member_details table when all i want is to return a single row that equals to the selected item in the drop down list.
Here is the php for it: i thought it would return the row which equaled the value of the drop down but its just listing it all.
<?php
if (isset($_POST['members'])) {
$ResultSet = getTableResults("member_details");
echo "<h1> Member Details </h1>";
echo "<table border='1' cellpadding='6'>";
echo "<tr> <th>Id</th> <th>Name</th> <th>Job</th> <th>Wage</th> <th>Hobby</th> ";
foreach ($ResultSet as $row) {
echo "<tr>";
echo "<td>" . $row ['member_id'] . "</td>";
echo "<td>" . $row['first_name'] . " " . $row ['second_name'] . "</td>";
echo "<td>" . $row['job'] . "</td>";
echo "<td>" . $row['wage'] . "</td>";
echo "<td>" . $row['hobby'] . "</td>";
echo "</tr>";
}
echo "<table>";
}
?>
If you want to see more code to make more sense of it please ask and il edit and update the question.
function getTableResults() {
$sql = "SELECT DISTINCT member_details.member_id, members.first_name, members.second_name, member_details.wage, member_details.job, member_details.hobby
FROM members
INNER JOIN member_details
ON members.member_id=member_details.member_id";
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
You do not have any Condition while requesting your information, getTableResults() fetches all Data that is stored to your table. You need to change that function and add a WHERE xy condition. Probably something like this:
function getTableResults( $id ) {
$sql = "SELECT DISTINCT member_details.member_id, members.first_name,members.second_name, member_details.wage, member_details.job, member_details.hobby
FROM members
INNER JOIN member_details
ON members.member_id=member_details.member_id WHERE member_details.member_id = '$id'";
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
Then Call the function with the requred member-id as parameter.
Anyway, I'd recommend you to inform yourself about prepared statements to prevent SQL-Injection here!
I've been confused about why this wont work! My query executes perfectly fine in all aspects, but when I added the if check on the $row value, the echo message goes as expected (if there are no results), but the else will not kick when there is a match in my query??? Why is this not working? Someone please ease my pain and set me straight!!
$row = mysql_fetch_array($result);
if (!$row) {
echo "Sorry brah. Nothing matches your search criteria.";
} else {
$i = 1;
while($row = mysql_fetch_array($result)) {
echo "$i - " . $row['first_name'] . " " . $row['last_name'] . " - " . $row['address'] . "<br />";
$i++;
}
}
$row = mysql_fetch_array($result); // this fetches the first row your result
...
in while loop you are again fecthing thr row from result. Which will not work if you have only one row in resul
use
if (mysql_num_rows($result) == 0) {
echo "Sorry brah. Nothing matches your search criteria.";
} else {
$i = 1;
while($row = mysql_fetch_array($result)) {
echo "$i - " . $row['first_name'] . " " . $row['last_name'] . " - " . $row['address'] . "<br />";
$i++;
}
}
try mysql_num_rows($result)==0 instead in the if statement