Getting the first row of the mysql resource string? - php

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!

Related

PHP mysqli query result echo with foreach loop

in my last project I used foreach loop to assign to every mysqli result a variable, like $r->mydata, but I formatted my pc accidentally, so I lost my core file and I can't remember how exactly I did that. I remember that I did something like this
$result = $db->query("SELECT * FROM data");
if($result->num_rows){
while ($row = $result->fetch_object()) {
foreach ($row as $r){
$row[] = $r;
}
}
}
And I can access the result from outside the while loop like this:
<?php echo $r->mydata ?>
Can anyone edit my code so it will work like before?
it would be easier to use
$rows=$result->fetch_all(MYSQLI_ASSOC);
rather than looping through all the rows and building an array.
Maybe you don't remember how you did it, but if you did it once you should know at least which approach you followed to solve this, let help you to understand the code first:
$result = $db->query("SELECT * FROM data");
if($result->num_rows>0){
//iterating only if the table is not empty
while ($row = $result->fetch_object()) {
//Here you are iterating each row of the database
foreach ($row as $r){
//Here you are iterating each column as $r
//and (trying) adding it again to the $row array
$row[] = $r;
}
}
}
Why would you like to access to the $row outside the loop, if what you want to do is print each row, you can do it inside the loop:
$result = $db->query("SELECT * FROM data");
if($result->num_rows>0){
while ($row = $result->fetch_object()) {
foreach ($row as $r){
echo $r.'<br>';
}
}
}
If you do something like what follows, what part of the 'printed' data do you need? You may have been 'specializing' the result set by eliminating the rows to only use a single row...
$result = $db->query("SELECT * FROM data");
$r = new stdClass();
// Only loop if there is a result.
if ($result)
{
$r->myData = []; // You aren't exactly clear on 'myData'. In this instance, I am setting the rows inside of it.
while ($row = $result->fetch_object())
{
$r->myData[] = $row;
}
$result->close(); // Free result set
}
print_r($r->myData);
$records = array();
$result = $db->query("SELECT * FROM data");
if($result->num_rows){
while ($row = $result->fetch_object()) {
$records[] = $row;
foreach($records as $r);
}
}
and now you can access the result from any place in the page,example echo inside html h1:
<h1>My name is: <?php echo $r->name ?></h1>

PHP and MySqli getting all results

I have 2 rows of data in my database and I am trying to fetch all rows
$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$results = mysqli_fetch_assoc($query);
I have tried mysqli_fetch_assoc, mysqli_fetch_row, mysqli_fetch_array all of them just return 1 row of data.
mysqli_fetch_*() functions except mysqli_fetch_all(), if supported, fetch one row. Loop and fetch:
while($row = mysqli_fetch_assoc($query)) {
print_r($row);
//or you can echo $row['username'] etc...
//or store in an array to loop through later
$rows[] = $row;
}
If you use mysqlnd there is a mysqli_fetch_all() or use:
if(!function_exists('mysqli_fetch_all')) {
function mysqli_fetch_all($result, $resulttype=MYSQLI_BOTH) {
while($row = mysqli_fetch_array($result, $resulttype)) {
$rows[] =$row;
}
return $rows;
}
}
$results = mysqli_fetch_all($query);
But then you have to loop through all the returned rows anyway:
foreach($results as $row) {
print_r($row);
//or you can echo $row['username'] etc...
}
Switch to PDO to do it in a single go... Use PDOStatement::fetchAll
<?php
//.. Do the neccessary PDO connections...
$sth = $dbh->prepare("select username, email, is_admin from adminUsers");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
(or)
You need to loop through them... [MySQLi]
$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$res = array();
while($results = mysqli_fetch_assoc($query))
{
$res[] = $results;
}
print_r($res);
Use while loop for fetching all lines:
while ($result = mysqli_fetch_assoc($query))
{
// Rest of your code. See an example below
echo $result['username'];
}

How to reuse the resulted variable after executing a mysql query

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;
}
?>

PHP - how to use array in function?

I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function

Mysql query mysql_fetch_array

$data = mysql_query("SELECT * FROM users);
now the data is stored in the $data variable. I would like to store the mysql data in an array and return that.
$data_array = mysql_fetch_assoc($data);
This would store the first row (the first array) of the data.
now to store all the rows I was wondering what should I do.
The standard approach:
$res = mysql_query($sql);
$data = array();
while(($row = mysql_fetch_array($res)) !== false) {
$data[] = $row;
}
// now $data is an array with all rows
http://php.net/manual/en/function.mysql-fetch-array.php
Returns an array of strings that
corresponds to the fetched row, or
FALSE if there are no more rows.
This approach works with mysql_fetch_* functions.
while ($row = mysql_fetch_assoc($data))
{
array_push($data_array,$row);
}
If your result set is big, it's not a good idea to do that. It could use a lot of memory on the process.
Having said that, you could store the whole thing on an array like this:
<?php
$query="select * from table_xyz";
$result = mysql_query($query) or die(mysql_error());
$arr_table_result=mysql_fetch_full_result_array($result);
function mysql_fetch_full_result_array($result)
{
$table_result=array();
$r=0;
while($row = mysql_fetch_assoc($result)){
$arr_row=array();
$c=0;
while ($c < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $c);
$arr_row[$col -> name] = $row[$col -> name];
$c++;
}
$table_result[$r] = $arr_row;
$r++;
}
return $table_result;
}
?>
Got the code sample from the PHP site.
$res = mysql_query($sql);
$data = array();
while(($row[] = mysql_fetch_array($res)) !== false) {
}

Categories