Separate rows from a multi-row result in MySQL PHP - php

For the code below, $result will return 4 rows from my question_answers table which have the corresponding question_id.
At the moment I am fetching all 4 rows into the $answers variable. I was wondering how I could separate each row from the result and store them as separate variables so I could, say, printf them one at a time.
Thanks.
Edit: also, since the question_id column is an integer in the question_answers table and also in $question["question_id"], have I written my WHERE statement correctly? Thanks.
$result = mysqli_query($connection, 'SELECT FROM questions_answers WHERE question_id='".$question["question_id"]."' ORDER BY RAND()'); //Runs the select query to get the possible answers to the randomly selected question
if(mysqli_num_rows($result)>0){
$answers = mysqli_fetch_assoc($result);
//printf each row individually
}
else{
printf("ERROR: no answers for this question exist!");
}

You can do this like below:
$i=1;
while(${"row" . $i} = mysqli_fetch_assoc($result)){$i++;};
So if there are 4 results, you will get the rows in $row1, $row2, $row3 and $row4;
But more standard way is to save the rows in array and use the array afterwards:
while($rows[] = mysqli_fetch_assoc($result));
In this case, you can access the rows like $rows['0'], $rows['1'], $rows['2'] and $rows['3']

Related

get data from two tables and collect them in array and count rows of one table result

I had two tables named fixture_list and OneRecord where fixture_list has 3 columns named Team1, Team2, player whereas OneRecord has columns like Team1, Team2, id, status so here I want to select all the data of fixture_list and put them into array whereas I want to count the number of rows based on this where condition fixture_list.Team1=OneRecord.Team1 and
fixture_list.Team2=OneRecord.Team2 from OneRecord, actually I am not able to distinguish between selecting the data and putting it into the array and counting the number of rows because I just want to count the rows of one record only. I know things like joins and mysqli_multi_query() can be performed but do not know how...I want to perform this thing in single query please help.
<?php
require_once('connect.php');
$sql = "select * from fixture_list";
if($res = mysqli_query($con,$sql)){
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('players'=>$row[3],
'team1_name'=>$row[1],
'team2_name'=>$row[2]
));
}
mysqli_free_result($res);
}
echo json_encode (array("list"=>$result));
mysqli_close($con);
?>
You can use a sub_query to do this. I don't understand your question perfectly (try using capitals and punctuation marks), but this should be probably the format to use.
$sql = "SELECT `fixture_list`.`team1_name`,
`fixture_list`.`team2_name`,
(
SELECT count(`OneRecord`.`Team1`) as `total`
FROM `OneRecord`
WHERE `OneRecord`.`Team1` = `fixture_list`.`Team1`
AND `OneRecord`.`Team2` = `fixture_list`.`Team2`
) as `Total_Players`
FROM `fixture_list`
GROU BY `fixture_list`.`id`";
$result = array(); // keep this outside the while loop to ensure the array is made
if($res = mysqli_query($con,$sql)){
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$result[] = $row;
}
}
This would give you a $result array as follows:
array(
'team1_name' => 'TEAMNAME1',
'team2_name' => 'TEAMNAME2',
'Total_Players' => INTEGER_VALUE
)
The INTEGER_VALUE is the number of rows from the subquery. You can edit the WHERE part of the subquery to your liking
Then you can do this to create a json object:
echo json_encode($result);
This will echo it, which is ideal if you use it with an Ajax function for example.

Mysql Counting rows in a table and returning an integer [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Whats the best way to get total # of records in a mysql table with php?
When i run :
mysql_query("SELECT COUNT(col) FROM table");
I end up with something like this :
(Resource) mysql result #4
How can i only get an integer that represent the number of row in my table so that later i can use it to make a simpel check such as : $result < 10.
Many Thanks
You have two options.
Get the result from the resource returned by the count query:
$resource = mysql_query("SELECT COUNT(col) FROM table");
$count = mysql_result($resource,0);
Or, get the number of rows from the resource returned by the query (without count).
$resource = mysql_query("SELECT col FROM table WHERE col IS NOT NULL");
$count = mysql_num_rows($resource);
I would recommend that you use the first, the reason being is that it is unnecessary to extract all the data from the table when you only need the count.
Note I've added WHERE col IS NOT NULL on the second one in order to recreate the effect of count(col) as opposed to count(*), as it will only count the non-null values of col.
mysql_query returns a mysql resource. To get the query output use:
$result = mysql_query("SELECT COUNT(col) FROM table");
if (!$result) {
die('Error:' . mysql_error());
}
echo mysql_result($result, 0);
See more examples here: http://php.net/manual/en/function.mysql-query.php
EDIT
By the way, this will only count the number of rows with a non-null value in col. To get the total number of rows in the table, use count(*)
Two options.
SELECT COUNT(*)....
Do the normal query. And add this line after retrieving the resource.
$num = mysql_num_rows($resource);

How would I get all the values of a field in mysql using php?

I have 3 rows with 3 fields, one row is numbers, how do I get all of those numbers? in that field? LIKE mysql_fetch_rows() in a for loop doesn't work?
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
In this code, it was selected a "person" from table "people" that had id = 42. Only one row of results is expected so, all that is needed is $row = mysql_fetch_row($result);.
After this $row will be something like this: array(0 => 42, 1 => 'person#people.xx');.
To print the email, you access the second position of $row by echoing $row[1].
This is exactly what's going on php documentation about mysql_fetch_row()
On the other hand, if you expect several rows to be returned, from a query like: SELECT id, email FROM people WHERE email LIKE '%#people%', you should use mysql_fetch_array() with a while loop. You can see example at mysql_fetch_array() documentation
If you are asking how to get all three numerical values from three different rows in one result you should look into MySQL's GROUP_CONCAT()

Select multiple values from the same row?

I have a script and I want to return 5 values from the database that have the same category but it is only returning one. Any ideas?
Here's the script:
$result = mysql_query("SELECT Category FROM GameData
WHERE Title=\"$title\" ");
//returns category to search in next select
$row= mysql_fetch_array($result);
$results = mysql_query("SELECT Title FROM GameData
WHERE Category=\"$row[0]\" LIMIT 5 ");
$rows= mysql_fetch_array($results);
print_r($rows); //returns $title from first select query
I'm new to databases and MySQL so any help would be much appreciated.
mysql_fetch_array just fetch one row in one call use loop to fetch multiple records
while($row= mysql_fetch_array($results))
{
print_r($row); //returns $title from first select query
}
You must loop over all the results: mysql_fetch_array returns one result row, so you have to call it multiple times:
while($row = mysql_fetch_array($results)) {
// here process ONE row
}
mysql_fetch_array will only fetch one row : if you want to fetch several rows, you'll have to call mysql_fetch_array several times -- in a loop, typically.
For a couple of examples, you can take a look at its manual page ; but, in your case, you'll probably want to use something like this :
$results = mysql_query("SELECT Title FROM GameData
WHERE Category='...' LIMIT 5 ");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
// work with $row['Title']
}
mysql_fetch_array only returns one row, you would have to loop through the rows
see example at: http://php.net/manual/en/function.mysql-fetch-array.php
You should use following query in order to make things right.
SELECT `Title` FROM GameData
LEFT JOIN
Category ON Category.Id = GameData.Category
WHERE Category.Title = "$title" LIMIT 5
I assumed that Category has column Id.
I advise you to learn about JOINS.
Additionally, you may want to rename Category to Category_Id, and drop letter-case so Category would become category_id.

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Categories