how to add data to array using for loop in php? - php

I am making a mysql query . I want to add result to an array. suppose I am selecting all user from user table. I want to get everyones name. if the row=5 i want to save every name according to the row index.
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
//echo ($row);
$num=mysql_num_rows($query);
echo ($num);
for ($i=1; $i<=$num;$i++){
//here I want to save all name to an array.
}
Please help.

You might be looking for something like this:
$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
$rows []= $row;
}
Note that mysql_fetch_assoc() will just return false if there are no (more) records in the result set. So you don't need the call to mysql_num_rows()

$num = mysql_num_rows($query);
if($num > 0)
{
while($row = mysql_fetch_array($query)
{
$names[] = $row['name'];
}
}
That will create an array called $names which you can loop through later. Also, it's a good time to look into mysqli_* functions, or PDO.

Related

php mysql_fetch_array() not working as expected

$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}

Selecting multiple rows in a table

I need to select multiple comments (if there are any) based on the photo_id. As I understand it you can use the WHERE clause but I'm not exactly sure how to select multiple ones and store them in some kind of array?
e.g.
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
$row = $result->fetch_assoc(); // but there's more than 1 row
If for example $photo1id == 21, how do I get all the comments (2 in this case)? Some kind of while loop?
At the end of the PHP file I have this:
echo json_encode(array('photo1id'=>$photo1id));
I need to store each row in that array somehow because I need to retrieve the data in another PHP file using $.getJSON. Or perhaps there is a better solution to this.
Loop through it and generate an array -
while($row = $result->fetch_assoc()) {
$comments[] = $row;
}
After that you can send the array as json.
echo json_encode($comments);
Is there is more rows, you need to use a loop.
while ($row = $result->fetch_assoc()) {
// your code here
}
Try the code below:
//Run query
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
//While there is a result, fetch it
while($row = $result->fetch_assoc()) {
//Do what you need to do with the comment
}
If you don't want to print the code straight away you can just create an array:
$x=0;
while($row = $result->fetch_assoc()) {
$comment[$x]=$row['comment'];
$x++;
}

Filed name appearing on same line

Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);

retrieve all datas from selected column and store

$result = mysql_query("SELECT * FROM Race");
$rows = mysql_num_rows($result);
for ($i = 0 ; $i < $rows ; ++$i)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
above is probably an awkward method but it'll print out all datas stored in first column, which is good but now, I want to store each one of them into an array...
I tried
$array[$i]=$row[0];
and echoed it out, but it just prints"Array"...
I tried
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
...which does the same as code written before, i guess, since it too just print "Array".
Please help! Thank you!!
Do you use simple echo $array;? It's wrong. You can't output array this way.
Use this:
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
foreach($item in $array) {
echo $item."<br>"; // and more format
}
If you want to watch array contents without any format use (e.g. for debugging) print_r or var_dump:
print_r($array);
var_dump($array);
Advice: better to use assoc array.
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row['raceid'];
}
Advanced advice: better to use PDO and object results.
You SQL code will be invulnerable to SQL injections
Code will be more modern and readable.

mysqli - How to fetch a row without modifying the result set?

Is it possible to extract a value from mysqli_result without fetching a row i.e. without modifying the result set as I need it in full later in my code?
You can also point the iterator back to the beginning. ie..
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
{
//do stuff with the result
}
//back to the start
mysqli_data_seek($result,0);
now the pointer is returned to the beginning. mysqli_data_seek
You can get all and store in an array…
$results = [];
$sql = mysqli_query($con,"SELECT * FROM WHATEVER");
while ($row = mysqli_fetch_array($sql)) {
array_push($results, $row);
}
//Now $results is fully populated

Categories