Warning: mysql_fetch_array () expects parameter 1 to be resource, array given

4

I am currently learning to program in PHP for some tutorials on YouTube from "the newboston" (maybe they know it) and I am in the database part of mySQL.

In my program I try to query data from a table in mySQL but it throws me an error that says the following: Warning: mysql_fetch_array () expects parameter 1 to be resource, array given.

this is my code:

By the template

<?php

$con_error='Could not connect';

$mysql_host='localhost';
$mysql_user='root';
$mysql_pass='';
$mysql_db='new_database';

/*connect to server / database*/
$mysqlcon=@mysql_connect($mysql_host, $mysql_user, $mysql_pass) or die($con_error);

/*select database*/
mysql_select_db($mysql_db, $mysqlcon) or die($con_error);

From the page that runs it

    require 'database.php';

$query="SELECT * FROM comida ORDER BY id";

if ($query_run = @mysql_query($query)) {

    while ($query_run= mysql_fetch_array($query_run)) {
        $platillo=$query_run['platillo'];
        $calorias=$query_run['calorias'];

        echo ' <br> platillo '.$platillo.' ofrece '.$calorias.'<br>';
    }

} else {
    echo '<br> could not connect <br>';
}

I hope you can help me with this. Thanks in advance for the answers!

    
asked by INME 13.08.2016 в 22:47
source

1 answer

1

Problem

mysql_fetch_array() takes the result of a mysql_query() as a parameter. And this you are doing correctly for the beginning of the loop. However, you are overwriting the value of $query_run , so in the second iteration of the loop, it will not have the value of the result of the query.

That is, for the first row that you retrieve with the query, it is executed correctly:

while ($query_run= mysql_fetch_array($query_run)) {

But notice that a new value is assigned to $query_run .
Consequently, for the second row, when it is executed:

while ($query_run= mysql_fetch_array($query_run)) {
                                     ^^^^^^^^^^

It no longer has the result of mysql_query()

Solution

Use a different variable for the result of mysql_fetch_array() . Let's use $fila for example:

while ($fila = mysql_fetch_array($query_run)) {
    $platillo=$fila['platillo'];
    $calorias=$fila['calorias'];

    echo ' <br> platillo '.$platillo.' ofrece '.$calorias.'<br>';
}

Security Note

Apparently the tutorial you're looking at has been a little outdated. The mysql_* functions have become obsolete and present security problems. It is very important that you read the article How to avoid SQL injection in PHP? to see how to implement this correctly.

    
answered by 13.08.2016 / 22:59
source