MySQL Query only grabbing one row instead of multiple. Why? - php

I'm trying to grab multiple rows via these lines from the MySQL database:
$msg_sql = "SELECT * FROM ".TABLE_PREFIX."quotes ORDER BY rand(curdate()) LIMIT 3";
$msg_res = mysqli_fetch_assoc(mysqli_query($link, $msg_sql));
print_r($msg_res);
However, I only get 1 row back. Which is:
Array ( [id] => 1 [message] => test_message [Link] => link here )
I wish to get multiple rows (so multiple ID's)
Please tell me what I'm doing wrong. I'm still new to MySQL.

You must loop once for each row you fetch.
$result = mysqli_query($link, $msg_sql);
while ($item = mysqli_fetch_assoc($result)) {
print_r($item);
}

You need to loop through your results:
$results = mysqli_query($link, $msg_sql);
while ($msg_res = mysqli_fetch_assoc($results))
{
print_r($msg_res);
}

Related

Is there a better way to run multiple SQL queries to the same table using PHP?

I have a query that requests an ID (the PK) and an order number and throws them into an array. I then loop through the returned data in the array and run two more queries to find the number of times the order number shows up in the database and to get the invoice numbers that belong to that order number. The problem I'm seeing with this setup is that it is taking a while (around 9 seconds) to return the compiled data array. Is there a faster way to get the returned results I'm looking for?
I've tried to find some articles online and came across mysqli_multi_query. Is this the better route to make multiple queries to gather the type of data I am trying to get?
<?php
require 'config.php';
$sql = "SELECT id,internal_order_number FROM orders GROUP BY internal_order_number ORDER BY created_date desc LIMIT 0 ,50";
$query=mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception(mysqli_error($mysqli)."[ $sql]");
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData['line_id'] = $row["id"];
$nestedData['internal_order_number'] = $row["internal_order_number"];
$data[] = $nestedData;
}
$compiled_data = array();
// Loop through data array with additional queries
foreach($data as $line){
$new_data = array();
// Get item counts
$item_counts = array();
$get_count = " SELECT internal_order_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."' ";
$count_query=mysqli_query($mysqli, $get_count);
while ($counts=mysqli_fetch_array($count_query)){
if (isset($item_counts[$counts['internal_order_number']])) {
$item_counts[$counts['internal_order_number']]++;
} else {
$item_counts[$counts['internal_order_number']] = 1;
}
}
$product_count = $item_counts[$line['internal_order_number']];
// Get invoice numbers
$invoice_array = array();
$get_invoices = " SELECT invoice_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."'";
$invoice_query=mysqli_query($mysqli, $get_invoices);
while ($invoice=mysqli_fetch_array($invoice_query)){
if(!in_array($invoice['invoice_number'], $invoice_array)){
$invoice_array[] = $invoice['invoice_number'];
}
}
$invoices = implode(", ",$invoice_array);
$new_data['order_number'] = $line['internal_order_number'];
$new_data['count'] = $product_count;
$new_data['invoices'] = $invoices;
$compiled_data[] = $new_data;
}
mysqli_close($mysqli);
print_r($compiled_data);
?>
What, why are you doing basically the same query 3 times. You first one selects them all, you second query requires the same table making sure the first tables order number == the tables order number and the last just grabs the invoice number...?
Just do one query:
SELECT internal_order_number, invoice_number FROM table WHERE ...
Then loop through it and do what you need. You don't need 3 queries...

PHP MySQL dont get last selected

i have a mysql Table with some rows.
The Select gets one (LIMIT 1) row. After a counter it reloads and get random another row. But sometimes he get the same (cause random).
How can i setup that he dont get the last row?
The problem is, i cannot do that in mysql. I must do that in the SESSION or only on that site.
I tried that:
$_SESSION['ads'] .= ','.$adid;
put that adid in "ads" SESSION and read it before SELECT here
session_start();
$ads = substr($_SESSION['ads'], 1);
$ads = str_replace(",", "','", $_SESSION['ads']);
In the SELECT is that
AND id NOT IN ('".$ads."')
But sometimes, i dont know why, he save two items or something... i dont find out why, cause the SELECT is LIMIT 1
Any ideas how to do that or is there a mysql function?
For any reason, the script is load two times the SELECT or something
This is the code:
$query = "SELECT * FROM ads ORDER BY RAND() LIMIT 1;";
while($row = $result->fetch_assoc()) {
$adid = $row["id"];
$_SESSION['ads'][] = $adid;
}
echo 'adid: '. $adid;
print_r($_SESSION['ads']);
There he print like that:
Array
(
[0] => 6
[1] => 3
)
I dont know, why he puts 2 in there. Cause the echo of the $adid shows only one!
Try something like this maybe :
1/ Create a new session and create an empty array :
session_start();
if (empty($_SESSION['ads']))
$_SESSION['ads'] = array();
2/ Do you select and add the id in this array :
if (empty($_SESSION['ads']) {
// 1. Do your select with no where condition
// 2. Fetch the result
$data = /* result of the select */;
// 3. Add the selected id in your session array
$_SESSION['ads'][] = $data['id'];
} else {
// 1. Do your select but with a WHERE condition
$query = "SELECT...
WHERE id NOT IN ( " . implode( "', '" , $_SESSION['ads'] ) . " )";
// 2. Fetch the result
$data = /* result of the select */;
// 3. Add the selected id in your session array
$_SESSION['ads'][] = $data['id'];
}
Is it what you are looking for?

Fetching last 100 row from mysql not working | JSON fromat

I'm trying to fetch the last 100 row but only one row is being displayed as a result
here is my php code:
<?php
require_once("variables.php");
$db = new ezSQL_mysql($GLOBALS['database_username'],$GLOBALS['database_password'],$GLOBALS['database_database'],$GLOBALS['database_server']);
header('Content-Type: application/json');
echo "{\"office\":\"0\",\"dept\":{\"desk\":[";
$symbols = addslashes($_GET['symbols']);
$symbolsArr = explode(",", $symbols);
foreach($symbolsArr as $s) {
$last = $db->get_row("select * from data where name='$s' order by id desc limit 0,100");
$jsonArray = array('name' => $s,
'phone' => $last->phone,
'active' => $last->active);
echo json_encode($jsonArray);}
echo "]}}";
?>
UPDATE> based on recommendations below I have changed get_row to get_results but the code broken now and it's not displaying any error.
Read the documentation on the database class you are using (ezSQL):
----------------------------------------------------
Example 2
----------------------------------------------------
// Get one row from the database..
$user = $db->get_row("SELECT name,email FROM users WHERE id = 2");
echo $user->name;
echo $user->email;
You are issuing a statement that is specifically to fetch one single row.
What you want to use is get_results() method instead of get_row() method.
I re-read your question and see that you were doing limit 0,100 which returns 100 rows starting with 0 (first). i thought you were trying to cycle those rows but I can see you are actually trying to only get the last row... my bad, derp.. well here - you are reversed somewhat in your query - should be 100,1 as you want the 100th row and only 1 row.
$last = $db->get_row("select * from data where name='{$s}' order by id desc limit 100,1");
$jsonArray = array('name' => $s,
'phone' => $last->phone,
'active' => $last->active);
Since you are trying to get last 100 rows use following statement:
$last = $db->get_results("select * from data where name='$s' order by id desc limit 100");
instead of
$last = $db->get_row("select * from data where name='$s' order by id desc limit 0,100");
ezSql get_results is the method which you need to use for retrieving multiple results from database.

How to mysql_query from same table with different where clause in same php file

I have a table containing 4 articles with id 1,2,3 and 4 as well as ordering value 1,2,3,4.
They have separate columns for their title, image etc. I need to get them distinctly with where clause. So i did:
For article 1:
//topstory1
$sql_topstory1 ="SELECT * FROM topstory WHERE story_active='1' && story_order='1'";
$result_topstory1 = mysql_query($sql_topstory1);
$row_topstory1 = mysql_fetch_array($result_topstory1);
$story1_title = $row_topstory1['story_title'];
$story1_abstract = $row_topstory1['story_text'];
And for article 2
//topstory2
$sql_topstory2 ="SELECT * FROM topstory WHERE story_active='1' && story_order='2'";
$result_topstory2 = mysql_query($sql_topstory2);
$row_topstory2 = mysql_fetch_array($result_topstory2);
$story2_title = $row_topstory2['story_title'];
$story2_abstract = $row_topstory2['story_text'];
As I have to reuse them in a page.
PROBLEM IS, the first query works but the second one doesn't. It seems like MySql cannot execute two consecutive queries on the same table in a single php file. But I think there is a simple solution to this...
Please help me soon :( Love you guys :)
There are several possible reasons for the second query to fail, but the fact that it's the second query in the file does not cause it to fail.
I would expect that article 2 does not have the active flag set to 1, causing you to get an empty result set.
Another option is that you may have closed the mysql connection after the first query, then you can't execute another query. (General rule: don't close database connections. PHP takes care of that.)
Why not just get them both with 1 query?
$sql_topstory ="SELECT * FROM topstory WHERE story_active='1' && story_order IN(1, 2) ORDER BY story_order DESC";
$result_topstory = mysql_query($sql_topstory) or trigger_error('Query Failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result_topstory)) {
$title[] = $row['story_title'];
$abstract[] = $row['story_abstract'];
}
// Then to display
echo 'Story 1 is ' . $title[0] . ' with an abstract of ' . $abstract[1];
There are plenty of ways to do this, this is just a simple demonstration.
$query = <<<SQL
SELECT
story_title
, story_text
FROM
topstory
WHERE
story_active
ORDER BY
story_order ASC
SQL;
$result = mysql_query($query);
$stories = array();
while ($row = mysql_fetch_assoc($result)) {
$stories[] = $row;
}
Now you have an array of stories like so:
array(
0 => array(
'story_title' => ?
, 'story_text' => ?
)
, 1 => array(
'story_title' => ?
, 'story_text' => ?
)
)
Should be pretty easy to iterate through.

Why returns the first element of an array only?

$count =0;
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");
$result4= mysql_fetch_array($result3);
print $result4[$count].'<br>';
$count++;
}
mysql_free_result($result1);
mysql_free_result($result3);
Let's have a look at how mysql_fetch_array works - for example if you have table structure like
id | name | surname | role
1 John Smith user
2 Peter Qeep user
3 Mark Ziii admin
When you execute a query SELECT * FROM table and then loop $result = mysql_fetch_array($query), $result will always be an array(4) containing
[0] => id,
[1] => name,
[2] => surname,
[3] => role
Therefore, when you execute the query $result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");, in the first iteration, $count will be 0 which is the key for the result returned by the previous query, however in any further iteration it will increase and that will lead to an undefined key. This means that you have to stop using the variable $count and just use $result2[0] instead.
Also, way better approach to this would be using MySQL JOIN, in your example it would be SELECT w.fsyn FROM sbsw s JOIN wrsyn w ON s.fwid = w.fwid WHERE s.fword = "'.$searchText.'";
Please, use reasonable variable names and indent properly. You're getting one column from each row as you're only printing out once for each iteration over your rows.
Basically: For each row, print the value of a column.
The $count-variable decided which column, but it obviously didn't make sense at it counts the row you're at.
Something like this should do it: (not tested)
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2['fwid']."'");
$result4= mysql_fetch_row($result3);
for($x = 0; $x < count($result4); $x++){
print $result4[$x].'<br>';
}
}
mysql_free_result($result1);
mysql_free_result($result3);
Oh and I changed fetch_array to fetch_row in the inner loop to ease iteration.

Categories