How to reuse the resulted variable after executing a mysql query - php

I am executing a query like this (PHP + MySQL):
$query = "SELECT * FROM tablename WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
// PHP Statement
}
I want to use the same result again on the same page then i need to execute query again like this:
$query = "SELECT * FROM tablename WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
// PHP Code
}
then it works. But if I use only
while($row = mysql_fetch_array($result))
{
// PHP Code
}
Then it doesn't work. Is there any other way to use the result many times on the same page without executing query every time?
I know i can use the same result to make an array. but is there any other way?

I believe mysql_data_seek will do this for you.
<?php
function mysql_pointer_position($result_set) {
$num_rows = mysql_num_rows($result_set);
$i = 0;
while($result = mysql_fetch_array($result_set)) {
$i++;
}
$pointer_position = $num_rows - $i;
//Return pointer to original position
if($pointer_position <= $num_rows - 1) {
mysql_data_seek($result_set, $pointer_position);
}
return $pointer_position;
}
?>

Related

PHP if statements being ignored

I'm new to PHP and SQL. I'm trying to make a rule so that it will only show certain information for certain pages. The code I'm using is
include 'dbh-login.php';
$id = $_GET['id'];
$i = 1;
while ($i != 100) {
$sql = "SELECT * FROM ui_off WHERE id='$i'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] = $id) {
echo $row['title']."<br>";
}
$i++;
}
The if statement seems to have no effect on weather the script echoes the title or not.
You are missing == assignment. Here is the working code.
$id = $_GET['id'];
$i = 1;
while ($i != 100) {
$sql = "SELECT * FROM ui_off WHERE id='$i'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] == $id) {
echo $row['title']."<br>";
}
$i++;
}
Your code does not make any sense.
You are using a while loop and looping in it 100 times just to check if 1 row have the given id.
Why don't you search directly for the id? Your code will be cleaner and you will free some memory on the server by deducting 100 queries each time the page is opened.
$id = $_GET['id'];
$sql = "SELECT * FROM ui_off WHERE id!='100' AND link='$id'" ;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] != '') {
echo $row['title']."<br>";
}

multiple sql queries into one small and better query

I am using these queries in my php page and I think there is a better way to do the same thing.
$cms1 = getRow("select * from cms where cmsID=1");
$cms2 = getRow("select * from cms where cmsID=2");
$cms3 = getRow("select * from cms where cmsID=3");
$cms4 = getRow("select * from cms where cmsID=4");
$cms5 = getRow("select * from cms where cmsID=5");
I am printing the data from these queries like
<?=$cms['content']?>
<?=$cms2['content']?>
<?=$cms3['content']?> ....
Is there a better way to do this or to get all this data in one single query? I think I might get the result by using AS key in the query but I have no idea how.
function getRow($query)
{
$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
{
$row = mysql_fetch_assoc($rs);
return $row;
}
}
This can also be best achieved using
BETWEEN
in mysql
SELECT * FROM cms WHERE cmsID BETWEEN 1 AND 5;
For more information on Between clause, you can visit this Link
$arrData = array();
$result = mysql_query($query) or die(mysql_error());
while($row = $result->fetch_array()) {
array_push($arrData,$row);
}
print_r($arrData);
First of All change your function
function getRow($query)
{
$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
{
while($row = mysql_fetch_assoc($rs))
{
$record[$row['cmsID']] = $row;
}
return $record;
}
}
Then change your query
$output = getRow(select * from cms where cmsID in (1,2,3,4,5));
Then echo your output.
print_r($output);
use mysql IN
select * from cms where cmsID in (1,2,3,4,5)
You can use IN clause to replace many OR conditions
$sql = "select * from cms where cmsID in (1,2,3,4,5)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['cmsID'].' '.$row['content'];//output like :- 1 content
}
for($i=1;$i<=5; $i++) {
$cms1 = getRow("select * from cms where cmsID='".$i."'");
}

My SQL query using exception while getting data

I am using MySQL to get data from table but it shows an exception. Here is the code I am using. I am calling this using URL to test:
$userName=mysql_real_escape_string($_GET['userName']);
$query = mysql_query("SELECT * FROM UserCredentials where UserName='$userName' ");
http://celeritas-solutions.com/pah_brd_v1/productivo/getUserData.php?userName=jamshaid.ali
Here is the exception
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/content/i/h/u/ihus235/html/cs/pah_brd_v1/productivo/getUserData.php on line 74 []
Here is the full code
$userName=mysql_real_escape_string($_GET['userName']);
$query = mysql_query("SELECT * FROM UserCredentials Where UserName='$userName' ");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
?>
$query = sprintf("SELECT * FROM UserCredentials where UserName='%s'",mysql_real_escape_string($_GET['userName']));
$result = mysql_query($query);
if(result){
//do you code
}
Some suggestions -
Use isset() , like --
if(isset($_GET['userName'])) {
// Do the processing, most appropriate check whether form is submitted or not
}
Now your code will looks like-
// Sanatize the data, and make sure to safe your code from sql injections(prefer PDO or mysqli_)
if(isset($_GET['userName'])) {
$userName=mysql_real_escape_string($_GET['userName']);
$sql = "SELECT * FROM UserCredentials Where UserName='".$userName."'";
$query = mysql_query($sql, $conn) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
}
?>
echo $sql; and run it in phpmyadmin to check your query is forming correctly or not, use var_dump() and read error/warning/notices to track errors.

Web page not loading with PHP-MySQL code while outputting JSON

I am using the code below to get information from a database and make it into JSON (it may be wrong).
Unfortunately it won't load in my web browser, it just says it's loading but it doesn't finish. Please can you tell me what I am doing wrong.
$query = mysql_query("SELECT * FROM Posts ORDER BY date DESC") or die(mysql_error());
$array = array();
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row;
$postID = $row['id'];
while ($ra = mysql_fetch_assoc(mysql_query("SELECT * FROM Comments WHERE postID = '$postID'"))) {
$array['comments'] = $ra;
}
while ($rd = mysql_fetch_assoc(mysql_query("SELECT * FROM Likes WHERE postID = '$postID'"))) {
$array['likes'] = $rd;
}
}
echo json_encode($array);
You are executing mysql_query in the infinite loop:
on each iteration you query the database, and fetch the first row. Change it to
$res = mysql_query("SELECT * FROM Comments WHERE postID = '$postID'");
if (!$res)
{
// handle error
}
while ($ra = mysql_fetch_assoc($res))
{
....
}
And the same for your second query.

Getting the first row of the mysql resource string?

Here is my problem.
I need more than one row from the database, and i need the first row for certain task and then go through all the list again to create a record set.
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
$firstrow = //extract first row from database
//add display some field from it
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
Now, how to extract just the first row?
Using mysql_fetch_assoc() not only fetches a row, it also moves the internal pointer of the result set to the next row. To reset the result resource to the first row, you need to use mysql_data_seek().
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
$firstrow = mysql_fetch_assoc($result);
// reset the result resource
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
If you want to get all the rows from the first one again then try the following
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
if ( $row = mysql_fetch_assoc ($result){
$firstRow = $row;
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
}
More about mysql_data_seek here: PHP: mysql_data_seek - Manual
you can use Object oriented style :
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
if ( $row = $result->fetch_assoc()){
$firstRow = $row;
mysql_data_seek($result, 0);
while( $row = $result->fetch_assoc()) {
//display all of them
}
}
Each time you call mysql_fetch_assoc($result), you get a row. So, instead of doing it repeatedly in a loop, just do it once:
$result = mysql_query("...");
if ($row = mysql_fetch_assoc($result)) {
$firstRow = $row;
while ($row = mysql_fetch_assoc($result)) {
// all the rest
}
}
Disclaimer: this could be prettier code, but you get the idea!

Categories