A mysql_fetch_array in another - php

I've seen the question about "doing mysql_fetch_array" multiple times solved by stocking the result in another variable, or by resetting the mysql_fetch_array loop index for example...
But that's not what I need. I need to use 2 mysql_fetch_ array, one in another, like this :
$sql = mysql_query("SELECT step FROM cyclone_cities ORDER BY uid");
$inc = 0;
while ($row = mysql_fetch_array($sql,MYSQL_NUM)){
$selected = $row[0];
while ($row2 = mysql_fetch_array(mysql_query("SELECT ".$selected." FROM cyclone_players ORDER BY uid"))){
print_r($row2);
}
}
How can I make it to use two differents mysql_fetch_array indexes ?

Related

Understanding mysqli_fetch_array()

Is there a way to make the code below cleaner?
I wanted to access the rows of $query4week like this: $query4week[0].
But mysqli_query() returns an Object on which I don't know how to access its particular rows. So, using fetch_array and a for loop I decided to create my own index.
$sql2 = "SELECT * FROM meals ORDER BY RAND() LIMIT 7";
$query4week = mysqli_query($con, $sql2) or die(mysqli_error($con));
for ($i = 0; $result = mysqli_fetch_array($query4week, MYSQLI_ASSOC); $i++)
{
$meal4week[$i] = $result['meal'];
}
I am still learning PHP and yet quite weak with OOP topics, please be patient :-)
Do it in this way
$i = 0;
while ($result = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $result['meal'];
$i++;
}
should work.
You shouldn't need a for loop if your fetching an associative array.
$i = 0;
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $row['meal'];
$i++;
}
There are already some perfectly reasonable answers here, but this is a little long for a comment. If all you are creating is a numerically indexed array starting with index 0, you don't need to explicitly define the index.
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC)) {
$meal4week[] = $row['meal'];
}
should work just fine. No $i necessary.
mysqli_query returns you a resource which represents the query result. You need to use the mysql_fetch_* functions to iterate over the result row by row. So yes, you need some kind of loop, if you are interested in more than the first row.

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

PHP print from database without 'while'

I need to print one row from a table so a while loop isn't necessary, is there any other method?
You need not while.
Just do your while condition outside while 1 time.
i.e
$a=mysql_fetch_row($sql);
//use $a
instead of
while($a=mysql_fetch_row($sql)){
//use $a
}
if (($dbResult = mysql_query("SELECT ... FROM ... LIMIT 1")) !== false)
{
$row = mysql_fetch_array($dbResult);
echo $row['Column_Name'];
}
Just fetch one row, no need to always loop a retrieval.
$results = mysql_query("SELECT * FROM my_table WHERE user_id = 1234");
$row = mysql_fetch_assoc($results);
echo ($row['user_id']);
Do what you would have done inside the condition of your loop, and you'll be fine.

Echo the results of query based on its index

This is pretty basic but I can't seem to get it to work
I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the first result of this query with
<?php echo $row_people['name']; ?>
I could also create a loop and echo all the results.
But I really want to echo the results individually based on its index.
I have tried this, but it does not work.
<?php echo $row_people['name'][2]; ?>
Thanks for your help.
You can fetch them by their index using a WHERE clause.
$people = sprintf("SELECT name FROM people WHERE index='%d'", $index);
If you want to query all rows, you could store them into an array while looping over them:
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$totalRows_people = mysql_num_rows($people);
$rows_people = array();
while($row_people = mysql_fetch_assoc($people))
{
$rows_people[] = $row_people;
}
You might want to add the primary key to the returned fields and use it as the array index probably.
You can ORDER them by their index and then use a loop.
$people = "SELECT name FROM people ORDER by index";
You can use mysql_data_seek on the result object to seek to a particular row. E.g., to get the name value from row 2:
mysql_data_seek($people, 2);
$row_people = mysql_fetch_assoc($people);
echo $row_people['name'];
If you're doing this a lot it will be easier to gather all the rows together in a single array at the start:
$data = array();
while ($row = mysql_fetch_assoc($people)) $data[] = $row;
This way you can fetch any cells in the results trivially:
echo $data[2]['name'];

How Can I access the first result?

$tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'");
while( $row = mysql_fetch_assoc($tmp))
{
echo $row['commercial'];
}
I only want to access the first element.
not in a while loop
You can use mysql_fetch_row to retrieve the value like that ...
$row = mysql_fetch_row($tmp);
$commercial = $row['commercial'];
Well, just remove your while loop then. This will get the first (actually current) row:
$tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'");
$row = mysql_fetch_assoc($tmp);
echo $row['commercial'];
Another option is to use mysql_result:
$tmp = mysql_query('..');
$row = mysql_result($tmp, 0);
echo $row['commercial'];
Side note: If you only need one row, add LIMIT 1 to your query.
If you need just the first element, why don't you append LIMIT 1 to your query ?

Categories