Error displaying rows from MySQL tables - php

I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}

You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.

It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}

Related

Total Results versus Returned Results in PHP

I am using the following php to display the number of records returned in a db search.
$sql = "SELECT COUNT(id) FROM authorsbooks WHERE author LIKE '%$searchquery%'";
$query = mysqli_query($dbc, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$textline1 = "Your Search Returned (<b>$rows</b>) Records";
<?php echo $textline1; ?>
This seems to work fine.
However, I cannot get the total number of records in the actual db to display.
Can anyone explain a way of getting the total number of records in the database. Btw, I have tried using $total = mysqli_num_rows($query) but it keeps returning 1 as an answer. Thanks for any help.
For that you've to fire another SQL query. Like this,
$sql = "SELECT COUNT(id) FROM authorsbooks";
$query = mysqli_query($dbc, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
echo $rows; // will return total rows in database.
SELECT COUNT(*) FROM authorsbooks
It's true that $total = mysqli_num_rows($query) should return one row. When you do a SELECT COUNT(*) then the query returns 1 row telling you how many matches there were in the table.

incorrect result display from database

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

PHP PDO Row Counting

i want to check the rows if there are any events that are binded to a host with host_id parameter, everything is well if there is not any events binded to a host, its printing out none, but if host is binded to one of the events, its not listing the events, but if i remove the codes that i pointed below with commenting problem starts here and problem ends here, it lists the events. I'm using the fetchAll function above too for another thing, there is not any such that error above there, but with the below part, it's not listing the events, how can i fix that?
Thanks
try
{
$eq = "SELECT * FROM `events` WHERE `host_id` = :id AND `confirmed` = '1' ";
$eq_check = $db->prepare($eq);
$eq_check->bindParam(':id', $id, PDO::PARAM_INT);
$eq_check->execute();
//problem starts here
$count3 = $eq_check->fetchAll();
$rowCount = count($count3);
if ($rowCount == 0)
{
echo "None";
}
//problem ends here
while($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) )
{
$_loader = true;
$event_id = $fetch['event_id'];
$event_name = $fetch['event_name'];
$link = "https://www.mywebsite.com/e/$event_id";
echo "<a target=\"_blank\" href=\"$link\"><li>$event_name</li></a>";
}
}
catch(PDOException $e)
{
$log->logError($e." - ".basename(__FILE__));
}
Thank you
You can't fetch twice without executing twice as well. If you want to not just re-use your $count3 item, you can trigger closeCursor() followed by execute() again to fetch the set again.
To reuse your $count3 variable, change your while loop into: foreach($count3 as $fetch) {
The reason that it is not listing the events when you have your code is that the result set is already fetched using your fetchAll statement (The fetchAll doesn't leave anything to be fetched later with the fetch).
In this case, you might be better off running a select count(*) to get the number of rows, and then actually running your full query to loop through the results:
An example of this in PDO is here:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
Note that you cannot directly use rowCount to get a count of rows selected - it is meant to show the number of rows deleted and the like instead.

PHP Zend - Execute to get a rowset and total number of records

I encounter some problem where i want to execute a SQL statement and get the total number of records + all the records.
$strSQL = "SELECT * FROM table WHERE ProjectID = 1 ";
$stmt = $db->query($strSQL);
$total = count($stmt->fetchAll());
while ($row = $stmt->fetch()){
..No More Record Shown here..
}
but there is no more record in the while loop after i execute fetchAll, i believe I need to get back to the first row or something, anyone know how to fix this?
You've already fetched all the records with fetchAll(). So when you call fetch(), there are no more records to read. Try storing the return value of fetchAll() in a variable and iterating through that. Something like this:
$strSQL = "SELECT * FROM table WHERE ProjectID = 1";
$stmt = $db->query($strSQL);
$allRows = $stmt->fetchAll();
$total = count($allRows);
foreach ($allRows as $row){
// process each $row
}

Categories