Multiple loops on mysql query - php

Probably simple but cant get my head around this simple task...
$query = "SELECT * FROM myTable WHERE this = that";
$result = mysql_query($mycon, $query);
while ($tablerow = mysql_fetch_assoc($result) {
do this
}
Can I rerun this while loop on the same $result without rerunning the query?
i.e.:
while ($tablerow = mysql_fetch_assoc($result) {
do something else using the same data
}
Thanks

Yes you can use the while loop again but after every while loop place this code:
mysql_data_seek($tablerow , 0);
As, this above function always resets the pointer to its starting point in loop.
Find the full code below:
$query = "SELECT * FROM myTable WHERE this = that";
$result = mysql_query($mycon, $query);
while ($tablerow = mysql_fetch_assoc($result) {
do this
}
mysql_data_seek($tablerow , 0);
//Do something you want
//Then again
while ($tablerow = mysql_fetch_assoc($result) {
do this
}
mysql_data_seek($tablerow , 0);
For security purpose and mysql is deprecated also, always try to use mysqli or PDO.
I hope, this may be helpful to you.

This will cause duplicate code which is a bad practice.
Use the same loop.

Related

I'm trying to create JSON from a comma delimited array

I need to output like this.
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.6192875","lng":"77.0261699"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6236227","lng":"77.0317984"},{"name":"","lat":"28.6244627","lng":"77.0322383"},{"name":"","lat":"28.6245415","lng":"77.0331425"},{"name":"","lat":"28.6245418","lng":"77.0331053"},{"name":"","lat":"28.6246156","lng":"77.0322415"},{"name":"","lat":"28.6242647","lng":"77.0316073"}
PHP Script
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)) {
$json_array = json_encode($row);
print_r($json_array);
}
Current Output
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.6192875","lng":"77.0261699"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6236227","lng":"77.0317984"}{"name":"","lat":"28.6244627","lng":"77.0322383"}{"name":"","lat":"28.6245415","lng":"77.0331425"}{"name":"","lat":"28.6245418","lng":"77.0331053"}{"name":"","lat":"28.6246156","lng":"77.0322415"}{"name":"","lat":"28.6242647","lng":"77.0316073"}
Thanks
You need to create the entire object you need before calling JSON encode:
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql); //You need to switch to mysqli , mysql is no longer a valid choice
$json_array = [];
while ($row=mysql_fetch_assoc($result)) {
$json_array[] = $row;
}
$jsonString = json_encode($json_array);
print_r($jsonString);
There are multiple ways to solve your "problem".
But first, don't use mysql_* functions => deprecated in PHP 5.5
Use mysqli_* functions instead.
If you have just a few hundred rows, you maybe could build an array with all items, like Paul Crovella and apokryfos said.
But if there are a multiple thousands of rows, you should prefer to write them out as quick as possible and don't save them to your RAM. Because PHP has limited space in RAM.
Maybe you could try it without loop:
$conn = mysqli_connect('host','username','password','database')
$query = 'SELECT name,lat,lng FROM `in_point_creation` WHERE 1';
$result = $conn->query($query);
$data = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($data);

php statement for multiple users not working

I am helping in some PHP design for a friends text game and have come to a stump.
I have scheduled a cron job to call the following page / following code, which is working correctly
<?php require("connect.php"); ?>
<?php
$sql = "SELECT id, name, health FROM users";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$id = htmlspecialchars($row->id);
$name = htmlspecialchars($row->name);
$health = htmlspecialchars($row->health);
$sql = "SELECT * FROM property WHERE living='1' AND ownerid='$id'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$OwnerName = htmlspecialchars($row->ownername);
$OwnerID = htmlspecialchars($row->ownerid);
$RaidPropBonus = htmlspecialchars($row->raidperc);
$RaidPropMoney = htmlspecialchars($row->raidcash);
$PropertyLvl = htmlspecialchars($row->proplvl);
$Living = htmlspecialchars($row->living);
if($PropertyLvl == '5' && $Living == '1'){
if($health < '100'){
$result = mysql_query("UPDATE users SET health=$health + '1' WHERE id='$id'")
or die(mysql_error());
} else { }
} else { }
}
}
?>
Although this only works for ONE user only. I cannot understand why this is. Any other logged in / out accounts that have met the criteria have been ignored. I can maybe only think I am missing a loop? As the ID that is being met first is number 1 and it has stopped there?
Anybody advice at all maybe?
UPDATE - It seems correct I need to get a loop in there, but am so far failing to get this loop working correct. No matter where I seem to amend / add a loop it does not help. Please may somebody suggest anything?
UPDATE2 - As requested, updated with the new version of loop
For what I've understood, the loops should be made on the mysql_fetch_object that will get the each row from the query.
Take a look at the snippet
<?php
require("connect.php");
// here prepare the $userQuery (the one that fetches all users)
// then the first loop that will read each usew row
// AFAICT this should afect all script
while($userRow = mysql_fetch_object($userQuery))
{
// prepare data fetched from the $userQuery
// prepare the $propertyQuery (the one that fetches all properties of the user)
// then the second loop to read all user property rows
// and this will afect the updates
while($propertyRow = mysql_fetch_object($propertyQuery))
{
// prepare data fetched from $propertyQuery
// add logic here
}
}
?>
Also #Matthew Carpenter had a valid point, that mysql_* is deprecated, you should consider in using mysqli_*, or in my opinion take a look at PDO

I Need to Write the Same mySQL Query Twice

Near the top of a PHP page I have a mySQL query followed by a do-while loop.
$query_offer = "SELECT offer, offer_text FROM ad_offers WHERE hid LIKE '$hid' AND show_from < CURRENT_DATE() AND show_to > CURRENT_DATE()";
$offer = mysql_query($query_offer, $MySQL_extranet) or die(mysql_error());
$row_offer = mysql_fetch_assoc($offer);
do {
SOME PHP STUFF
}while($row_offer = mysql_fetch_assoc($offer));
Then further down the page I want to repeat the same do-while loop with different PHP code inside it. But it doesn't work. It seems as if the system has forgotten the results of the query after doing the first do-while. If I precede the second do-while with a repeat of the original query, it works. But that seems very messy, and surely it is unnecessary to write the same query twice on the same page.
Any advice would be appreciated. Thanks.
Assign the rows to an array then reuse the array
$Offers = array();
while($row_offer = mysql_fetch_assoc($offer)) {
$Offers[] = $row_offer;
}
then further down your code loop over $Offers
after looping the data once, you need to do
mysql_data_seek($offer, 0);
More info: http://php.net/manual/en/function.mysql-data-seek.php
Note: This extension is deprecated as of PHP 5.5.0
Assign the results to an array and iterate over that again, or create function which you can call whenever you need it.
<?php
function getOffers($hid) {
$offers = array();
$query = mysql_query('SELECT ...');
while($offer = mysql_fetch_assoc($query)) {
array_push($offers, $offer);
}
return $offers;
}
$offers = getOffers($hid);
// use $offers here
// or here
// or recall getOffers($hid)
Anthony.

PHP mysqli_fetch_assoc to store data in an array

I have a list of url's(link) in my database and can echo the data to the page fine but instead of outputting it, I need to store that info(I was thinking an array) into a variable to perform php tasks using the provided links. I have yet to figure out how to do this.
The code has been updated I removed any references to using the soon to be deprecated mysql_* functions and opted for the mysqli version.
Heres my code
$query = "SELECT `Link` FROM `Table1` WHERE `Image` ='' AND `Source`='blah'";
if ($result = mysqli_query($dblink, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$link = $row['Link'];
// echo ''.$link.'<br>';
$html = file_get_html($link);
foreach ($html->find('div.article') as $e) {
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
echo $imgsrc;
}
}
}
This code is working through one iteration: It will find the first link stored in the DB, use that $link in the bottom foreach() statement and output the desired result. After the first iteration of the loop, an error occurs stating:
"mysqli_fetch_assoc() expects parameter 1 to be a mysql result"
I think I understand why the problem is occurring - Since the $result is declared outside of the while loop, it is never set again after the first iteration/or changes in some way.
or
I should be using mysqli_free_result() possibly, If that were the case I am not sure where it would go in the code.
Thanks for any help you can offer!
When you do this:
$result = mysqli_query($dblink, $query);
The functions return a link identifier you store in $result. This identifier we need to pass to fetch functions in order to be able to show it from which result to fetch. It shouldn't be changed until you are done fetching all the results you want.
This goes right the first time:
$row = mysqli_fetch_assoc($result)
But then, in the foreach, you overwrite that variable with other information:
$result = $e->find('img', 0);
As such, when the next iteration comes around, it is no longer a valid result identifier, so MySQL doesn't know what to do with it.
The fix is actually rather simple, you need to change the name of the variable you are using in the foreach:
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
Becomes:
$found= $e->find('img', 0);
$imgsrc = $found->src . '<br>';
And voila, it should work...
Your snippet is full of potential errors:
1) Not checking if query succeeded
$query_run = mysql_query($query)
You execute a query, but you never check if your query succeeded by verifying if $query_run is an actual resource and not FALSE.
2) Validation of rows returned
Your validation for the number of rows returned by the query is useless:
if (mysql_num_rows($query_run)==NULL) {
echo 'No results found.';
}
This is never true, as mysql_num_rows() returns an inte or FALSE, never NULL.
3) Use of variable with potentially invalid value
Using
while ($query_row = mysql_fetch_assoc($query_run)) { ... }
is risky as you never check if $query_run is an actual resource, which is required by mysql_fetch_assoc().
4) Misunderstanding of while loop
The following lines are probably wrong too:
while ($query_row = mysql_fetch_assoc($query_run)) {
$link = $query_row['Link'];
// echo ''.$link.'<br>';
}
$html = file_get_html($link);
You iterate over all rows returned by the query. After the while loop exits, $link only contains the value of the last row as single variable cannot contain the values of multiple rows.
Conclusion
I strongly recommend you improve your error checking and improve the overall quality of your code. Also consider using one of the newer extensions like mysqli or PDO, the mysql extension is deprecated.
If you want to add all links to an array try this:
$link[] = $query_row['Link'];
Instead of:
$link = $query_row['Link'];
You were close but you weren't using square brackets you were using parentheses as shown here:
$link = $query_row($link);
Also, try taking $query_run out of the if statement. It should look something like this:
$query = "SELECT `Link` FROM `Table1` WHERE `Value1` ='' AND `Source`='blah'";
$query_run = mysql_query($query);
if ($query_run) {
echo 'Query Success!<br><br>';
if (mysql_num_rows($query_run) == NULL) {
echo 'No results found.';
}
while ($query_row = mysql_fetch_assoc($query_run)) {
$link[] = $query_row['Link'];
// echo ''.$link.'<br>';
}
$html = file_get_html($link);
foreach ($html->find('div.article') as $e) {
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
echo $imgsrc;
}
}
You should revisit the PHP Language Reference.
The foreach loop syntax is
foreach($array as $element)
or
foreach($array as $key=>$value)
But you seem to have other weak points that I fear are not in the scope of Stackoverflow to mend. For example your own code would work quite well by just moving a single } from line 11 down a few lines.

PHP Variable - Multiply pages

I have a functions.php page, I have included in ALL my other php pages. What I want is a function in my functions.php page, I can use in all the other pages.
I have tried this:
function getSetting()
{
$r=mysql_query("SELECT * FROM settings");
if(mysql_num_rows($r) == 0)
return false;
else
$sdata=mysql_fetch_assoc($r);
return $sdata;
}
The thing I want to, I want to get the data from the row next to the name in the following picture: http://awesomescreenshot.com/0bci8x472
Example:
If I write $sdata['sitename'], I want it to output "ptcify"
Thanks!
Try using mysql_fetch_array() with MYSQL_ASSOC as documented at this link http://www.php.net/manual/en/function.mysql-fetch-array.php.
There are a lot of things you could do to further improve your code implementation i.e OOP, using better database abstraction libraries(even switching to PDO insted of PHP_MYSQL is an improvement), but this should work straight of the bat.
Most questions usually have a ? in them somewhere, to indicate an actual question. I'm not sure what the problem with your code is, but I'm guessing you're only getting a single "setting" result - if that query returns multiple rows, you have to loop over the result set and get each row, THEN return:
$r = mysql_query(...) or die(mysql_error());
$sdata = array()
while ($row = mysql_fetch_assoc($r)) {
$sdata[] = $row;
}
return $sdata
edit
$sql = "SELECT setting_name, setting_value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
$sdata = array();
while($row = mysql_fetch_assoc($result)) {
$sdata[$row['setting_name']] = $row['setting_value'];
}
return $sdata;

Categories