PHP while loop. Why does this work? - php

I'm creating my first php site using tutorial for reference. I can't get my head around why the following works:
while ($row = mysql_fetch_array($result)){
echo $row[1]. " ".row[2]."<br/>";
}
Specifically, how does the loop increment to the next row?
UPDATE:
Thanks to all who bothered to provide an answer, including those who implored me to RTM. My problem was not understanding how while loops work, rather simply I couldn't see how the loop increments.
THE ANSWER:
From the PHP docs,
mysql_fetch_array: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead
I see now, all is well.

You can rewrite that code to this equivalent:
$row = mysql_fetch_array($result); // fetch and advance
while ($row !== false) { // compare result against false
echo $row[1]. " ".row[2]."<br/>";
$row = mysql_fetch_array($result); // fetch and advance
}
An assignment yields a value which can then be used in a condition, though it's a good practice to put parentheses around the assignment:
// fetch and advance, compare fetched result against false
while (($row = mysql_fetch_array($result)) !== false) {
echo $row[1]. " ".row[2]."<br/>";
}

mysql_fetch_array() will take a $result and save into $row in form an array. Using while loop, your program will loop the data in the array from the beginning until the end.
By the way, your codes should be like
while ($row = mysql_fetch_array($result)){
echo $row['someData1']. " ".row['someData2']."<br/>";
}
If you want to iterate through the index, then the code looks like following but it will print the word Array as you will print the result in "that" specific index.
$indexCounter = 0;
while ($row = mysql_fetch_array($result)){
echo $row[$indexCounter]."<br/>";
}
Hope this helps! Thank you.

The mysql_fetch_array take the first element of $result then is $result have elements this work... is like take cards from a deck

Take a read though the PHP While documentation. It might also be useful to learn what mysql_fetch_array() does and how it works. After you're done reading about that, don't use the mysql_* functions again because they're deprecated. Instead, use mysqli_* or PDO.

Related

Query more slow

I do a query but does not show anything on the screen and when I opened the page where I do the query is slow and does not show anything
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row=mysqli_num_rows($result)){
echo $row['COMPONENTE'];
}
mysqli_num_rows() will only use for getting no of rows not for row data.
You need yo use mysqli_fetch_*()
while($row=mysqli_fetch_array($result)){
echo $row['COMPONENTE'];
}
Why this query slow? Because you are using infinite loop here, always TRUE.
while($row=mysqli_num_rows($result))
One more story, I hope you are using session_start() in your file, but suppose that if $_SESSION not found or not start than your query will failed.
In last, this is just a suggestion regarding Naming Convention, you are using column name in small letter, capital small, full capital, this is not related to answer but you must need to learn about this art.
this will help you to understand Naming Convention: Database, Table and Column Naming Conventions?
This reference will help you to understand how mysqli_fetch_array() works: http://php.net/manual/en/mysqli-result.fetch-array.php
Please try with this one for return value and if you need number of raw then the statements will be different.
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row=mysqli_fetch_array($result)){
echo $row['COMPONENTE'];
}
As others have pointed out, you have mixed up the mysqli_num_rows function, here I am using it to print the number of results found, then loop through the results after converting the mysqli result object to an array named $row
echo 'Found '. mysqli_num_rows($result) .' results';
while ($row = mysqli_fetch_array($result)) {
echo $row['COMPONENTE'];
}
You are fetching record but using mysqli_num_rows() which return total number of rows/records replace it with mysqli_fetch_array() here is the working example.
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row = mysqli_fetch_array($result)) { //replace mysqli_num_rows with mysqli_fetch_array
echo $row['COMPONENTE'];
}

returning results from a column into an array

I am very new to PHP and I realise I have a lot to learn, especially about SQL injection attacks and the new php 5.5 oo stuff.
However, whilst I am learning I try to play about a bit and experiment and I have come across a problem. I need to get all results from one column (team_name) of my query into an array (zero indexed would be easier) so that I can put those results into a foreach loop to create a fixture list. For example - this is what I would like to do with the data...
foreach ($teams as $team) {
foreach ($teams as $opposition) {
if ($team != $opposition) {
echo "$team versus $opposition";
}
}
}
So my sql query is as follows...
$query="select * from pool_a";
$result=mysql_query($query);
$num=mysql_num_rows($result);
Then I can easily output the data I am looking for as follows;
echo "<table>";
for ($i=0;$i<$num;$i++) {
$teams=mysql_result($result,$i,'team_name');
echo "<tr><td>$teams</tr>";
}
echo "</table>";
But what I can't do is get the data into an array. I thought that data that came back from a msql_query such as the above always came back as an array, no matter the number of results, but if I run an is_array() check on $teams, it returns false.
I have tried using explode (after adding a comma after each team name and trimming the last one off) and then using a foreach loop but it only ever returns the value associated with the index [0]. I should add here that although the key is 0, the actual value I get is the LAST in the list when echoed as above, which I also don't understand.
Any help would be much appreciated.
Thanks
$team_names = array();
while ($row = mysql_fetch_assoc($result)) {
$team_names[] = $row['team_name'];
}
mysql_fetch_assoc, mysql_fetch_row, and mysql_fetch_array all return a row as an array (they differ in how it's indexed). But mysql_result just returns a single item from the result, so it doesn't return an array.
You could do the same thing as above with your use of mysql_result, but you still have to push them onto the result array yourself:
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[] = $team;
}
To get the results of the query into an array, you can do this
$query="select * from pool_a";
$result=mysql_query($query);
$result_arr = mysql_fetch_array($result);
$num=mysql_num_rows($result);
However, consider using the PDO drivers to connect to the database. It's far superior to doing it procedurally, and it's safer as Prepared Statments will help protect you against injection attacks. The method you're using is deprecated.
Instead of using mysql_result try using mysql_fetch_array($result, MYSQL_ASSOC)
This function will give you an array of whatever your result from MySQL is.

How to perform a function for every row in a mysql array?

UPDATE: I solved it using a for loop:
for ($i=0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
ORIGINAL QUESTION:
This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.
here's the code
while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}
can you post the complete code? I think you forgot the database connection.
Try this:
$result = mysql_query("SELECT * FROM files") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
var_dump($row['name']);
}
This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.
Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.
Also, set error reporting to E_ALL like so.
error_reporting(E_ALL);
Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)
You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.
From your question it seems so simple, try this way it's working.
$sql="SELECT name From files";
$names = $db->query($sql);
while($name1 = $db->fetchByAssoc($names))
{
echo $name1['name'];
}

Using mysql_fetch_assoc and mysql_result together?

I am having great trouble trying to use mysql_fetch_assoc and mysql_result together in the same PHP script.
Originally (when not utilizing the mysql_result function) I was getting the required database values using a combination of mysql_query and mysql_fetch_assoc and everything was fine. Then i added 2 lines into my code to obtain certain ‘title’ field values using mysql_result.
Now if i run my script as it is below i will only receive 1 result even though there are 2 result. Then if i move my do/while loop up so that it is between the other 2 blocks of code (mysql_fetch_assoc and mysql_result lines) i will receive the desired 2 results.
I need my loop to come after the mysql_result section so putting the loop before it is not an option.
// connect to DB and get values
mysql_select_db($database, $mywebsite);
$query_not_related_before = "SELECT * FROM table limit 2";
$not_related_before = mysql_query($query_not_related_before, $ mywebsite);
$row_not_related_before = mysql_fetch_assoc($not_related_before);
// Extract just the results from the title field (the problem area!)
$before_essayid4 = mysql_result($not_related_before,0, 'title');
$before_essayid5 = mysql_result($not_related_before,1, 'title');
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
Plase help,
Many thanks,
David
I am unsure if this will solve your problem but I think you should "seek" the result back.
mysql_data_seek ($not_related_before, 0)
Also, check out the warning on the mysql_result page:
Calls to mysql_result() should not be
mixed with calls to other functions
that deal with the result set.
Hope this helps ;)
You get one row because the first already requested here:
$row_not_related_before = mysql_fetch_assoc($not_related_before);
So I think you have to move result pointer to beginning:
mysql_data_seek($not_related_before, 0);
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
A simpler solution would be to use 2D array's, i have always found the mysql functions to be a little cumbersome.
<?php
$result = mysqli_query(db_connect(),$query);
$result_out = array();
if(#mysqli_num_rows($result))
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))$result_out[]=$row;
foreach($result_out as $row)
{
echo "<br />".$row['title']."<br />";
}
?>
hth

MySQL, how to use returned data?

Well, I know there is a funciton mysql_fetch_array() and we can use it like this:
while ($row = mysql_fetch_array($result)) {
echo $row['name'] . "<br />";
}
But is there any other way? For example, if there is only one element that can be returned, and not an array.
Thanks)
see mysql_result():
Retrieves the contents of one cell from a MySQL result set.
If there's only going to be one row then you can just say:
$row = mysql_fetch_array($result);
Or you can use mysql_fetch_row if you want.
But I'd second Erik's comment to go with PDO. Here's a good tutorial making heavy use of PDO.
You could use mysql_result
$result = mysql_query($query) or die(mysql_error());
$scalar = mysql_result($result, 0);
For example, if there is only one
element that can be returned, and not
an array.
Nope.
Only array or a useless object you can get.

Categories