I currently have an array in php that stores product names, normally 5 - 10. I would like to create something where the results of a SQL query is matched against the array to make sure they are all correct, and if not to show an error.
So far I have put the results into an array, then ran the query to get the results. I believe I need to put some sort of while loop with the results of the query and check the array in that while loop?
You have the array with the product name($products) and the results of the query($row).
While you loop trough the results you can check if the element is present,otherwise echo error and break the loop:
While(...) {
if(!in_array($row['retrivedprod'],$products)) {
echo 'error';
break;
}
}
You can cycle while receiving results from db with a while loop and checking results with the in_array function http://php.net/manual/en/function.in-array.php
$availability = 0;
$cart_products = array("book", "album");
$available_products = array();
while($row = mysql_fetch_array($result)) {
$available_products[] = $row['product'];
}
foreach($cart_products as $key => $value){
if (in_array($value, $available_products)){
$availability = 1;
}
}
Related
This question already has answers here:
Mysqli query doesn't work twice
(2 answers)
Closed 5 years ago.
I'm retrieving some data from a mysql database. There are two loops which uses the same result set.
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
This loop ends with success. then in the same page I have the following loop.
while ($row = mysqli_fetch_array($newsQuery)) {
echo $row["news_content"];
}
This loop doesn't return anything even if there are content in the table. When I try it in the first loop. the content is displayed correctly. Any idea on what I'm doing wrong.
From PHP's mysqli_fetch_array DOCS:
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
You are using a 'while' loop on $row = mysqli_fetch_array($newsQuery)
This means the loop will keep going untill mysqli_fetch_array($newsQuery) returns NULL.
This is the reason why you cant use that loop again, since mysqli has finished fetching the results and the mysqli_fetch_array($newsQuery) now returns NULL untill you make a new query.
Try populating a variable with the results first, then loop on that variable:
$results = array();
while ($row = mysqli_fetch_array($newsQuery)) {
$results[] = $row;
}
foreach ($results as $key => $row) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
foreach ($results as $key => $row) {
echo $row["news_content"];
}
While it is best to avoid logic that results in looping through a result set twice, if necessary you need to reset the result set back to the start:-
mysqli_data_seek($newsQuery, 0);
Because you already fetch the value of $newsQuery Try this code
//temporary save the news content into array
$content = array();
$x=0;
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
$content[$x]= $row["news_content"];
$x++;
}
and if you want to retrieve it
//now retrieve it
for($y=0; $y<count($content); $y++)
{
echo $content[$y]+"<br/>";
}
I'm experimenting with MySQLi and using the following code to check differences for how I should approach my array formatting/usage for fetch_array(MYSQLI_ASSOC);
here is my code:
include "Database.php";
$ArrayQuery = $mysqli->query("SELECT * FROM accountinformation");
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
The problem is, that i'm using the same Variable for my while loop, the first one returns 3 then 3 Which is expected.
But the problem is, with my second query; it returns a blank array
array( ) when print_r();
and when I do:
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
For my Second while loop, it returns nothing for output.
I have checked my variables $ArrayResults and $ArrayResult are not duplicates, they are in fact unique.
Why is my second while loop returning nothing when my first one is working?
Update
When I produce a second query into the mixture with a different starting variable:
$ArrayQuer = $mysqli->query("SELECT * FROM accountinformation");
and modify my second while loop:
while ($ArrayResult = $ArrayQuer->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
I get the expected output? So is it a case of MySQLi not allowing the same parameters to be used twice throughout the script?
mysqli_data_seek
Adjusts the result pointer to an arbitrary row in the
result
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
mysqli_data_seek($ArrayQuery,0); // Addition Made Here
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
To re-use an already fetched array; you should use mysqli_data_seek(); (Notice I have added it above your `$Empty Variable) This should be the problem.
See the manual here:
http://us.php.net/manual/en/mysqli-result.data-seek.php
Think of this scenario; Why would you re-buy something you already own?
Fits perfectly in your case
Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.
ok i have this and it doesn't show all the rows when fetched from mysql database its like this:
mysql_select_db($database_config, $config);
$query_cat = "SELECT * FROM cat";
$cat = mysql_query($query_cat, $config) or die(mysql_error());
$row_cat = mysql_fetch_array($cat);
$arr = array("TIT" => $row_cat['title'],
"DES" => $row_cat['description']);
foreach($arr as $ar){
echo $ar;
}
now it only displays the first row and then stops why is it not displaying all the fields and i don't wanna use while loop for it can anyone explain me the problem??
EDIT: Well basically i want to work it like this
$p = "{TIT}{DES}";
foreach($arr as $k => $p){
$p = str_replace("{".$k."}", $v, $p);
echo $p;
}
Now the problem is not with str_replace its with the loop or database because the database rows are not incrementing and displays only one data.
This will always return the first row. you are fetching only once that will return only first row.
Instead you must fetch all the rows using fetch statement in loop
while($row_cat = mysql_fetch_array($cat)){
echo $row_cat['title'];
echo $row_cat['description'];
}
From PHP mysq_fetch_array documentation:
"Returns an array that corresponds to the fetched row and moves the internal data pointer ahead"
As far as I know, you cannot retrieve every row without using a loop. You should do something similar to this:
while($row_cat = mysql_fetch_array($cat)){
echo $row_cat['title'];
echo $row_cat['description'];
}
What I want to do here is to be able to assign the values from sql query into arrays.
And then compute for the total.
<?php
include('conn.php');
$qreports=query_database("SELECT S_PRICE, PID, QTY_PUR, ITEM_ID, CUSID, CNUM, Cust_Name, TDATE FROM prod_table, customer_credit, sales_trans_items WHERE prod_table.PID=sales_trans_items.ITEM_ID AND sales_trans_items.CNUM=customer_credit.CUSID AND sales_trans_items.TDATE='2011-02-06 09:14:09'","onstor",$link);
$grandtotal=0;
$customer="";
while($qrep=mysql_fetch_assoc($qreports)){
$pid=$qrep['PID'];
foreach ($pid as $k => $v) {
$sids=$v;
$qtypur=$qrep['QTY_PUR'][$k];
$sprice=$qrep['S_PRICE'][$k];
$customer=$qrep['Cust_Name'][$k];
$tdate=$qrep['TDATE'][$k];
$stot=$qtypur * $sprice;
$grandtotal =$grandtotal + $stot;
}
}
echo "Customer: ". $customer."<br/>";
echo "Profit: ". $grandtotal;
?>
I tried the query on phpmyadmin before I place it in the code, and it output this:
I think you misunderstood how mysql_fetch_assoc works: Every call returns one row from the result set. $grep is an array with structure columnname => value.
That also means that $qrep['PID'] cannot be an array and your foreach loop won't work. In every loop, $qrep['PID'] contains one of the values you see in the PID column in your screen shot.
I suggest you add print_r($qreq); in your while loop so you get more familiar with the structure of the array.
As each $qrep is an array itself, creating a result array is just adding each of these to a new array:
$result = array();
while(($qrep=mysql_fetch_assoc($qreports))) {
$result[] = $qrep;
}
Now you are performing some more computation where I am not sure what you want to get in the end but it seems you are multiplying each QTY_P with S_PRICE:
$total = 0;
foreach($result as $report) {
$total += $report['QTY_P'] * $report['S_PRICE'];
}
(You could however also compute this in your while loop)
Assuming you want to get the overall sum and the sum for each customer:
$total = 0;
$total_per_customer = array();
foreach($result as $report) {
$customer = $report['Cust_Name'];
if(!array_key_exists($customer, $total_per_customer)) {
$total_per_customer[$customer] = 0;
}
$price = $report['QTY_P'] * $report['S_PRICE'];
$total_per_customer[$customer] += $price;
$total += $price;
}
In the end, $total_per_customer is an array with customer names as keys and the sum of the prices as values. $total will contain the sum of all prices.
You question is a bit unclear, but i think the answer wont be far a way from the following suggested references:
As you loop through the rows use
something like $array[] =
$qrep['columnName'] to populate an
array.
Then, check out PHP's array_sum().