Convert mysql_result to mysqli

I am not a programmer and I know very little PHP, but I am trying to fix a code in the osCommerce store that gives the following error on PHP 5.4:

mysql_result (): The supplied argument is not a valid MySQL result resource

This is the code:

$products = $cart->get_products();
    for ($i=0, $n=sizeof($products); $i<$n; $i++) {
    $id_produto = (INT)$products[$i]['id'];
    $sql = tep_db_query("SELECT p.manufacturers_id,m.manufacturers_cep,m.manufacturers_name FROM products p
    LEFT JOIN manufacturers m ON m.manufacturers_id = p.manufacturers_id
    WHERE p.products_id = '$id_produto'")OR DIE(mysql_error());
    $id_fabricante = mysql_result($sql,'0','manufacturers_id');
    $cep_fabricante = mysql_result($sql,'0','manufacturers_cep');
    $nome_fabricante = mysql_result($sql,'0','manufacturers_name');

    $id_fabricantes[$id_fabricante]['peso'] += $products[$i]['quantity']*$products[$i]['weight'];
    $id_fabricantes[$id_fabricante]['cep'] = $cep_fabricante;
    $id_fabricantes[$id_fabricante]['nome'] = $nome_fabricante;

    }

      

I tried to change it and there are no more errors, but it still doesn't work. Is this the correct way to do it?

$products = $cart->get_products();
for ($i=0, $n=sizeof($products); $i<$n; $i++) {
$id_produto = (INT)$products[$i]['id'];
$sql = tep_db_query("SELECT p.manufacturers_id,m.manufacturers_cep,m.manufacturers_name FROM products p
LEFT JOIN manufacturers m ON m.manufacturers_id = p.manufacturers_id
WHERE p.products_id = '$id_produto'")OR DIE(mysql_error());

$row = mysqli_fetch_assoc($sql);
$id_fabricante = $row['manufacturers_id'];

$row = mysqli_fetch_assoc($sql);
$cep_fabricante = $row['manufacturers_cep'];

$row = mysqli_fetch_assoc($sql);
$nome_fabricante = $row['manufacturers_name'];

$id_fabricantes[$id_fabricante]['peso'] += $products[$i]['quantity']*$products[$i]['weight'];
$id_fabricantes[$id_fabricante]['cep'] = $cep_fabricante;
$id_fabricantes[$id_fabricante]['nome'] = $nome_fabricante;

}

      

+3


source to share


1 answer


No, this is not true. If you check manual , you can see that the second parameter is the string to retrieve in your result set. In the original example, you only retrieve data from the first row - 0

- and nothing else.

In your mysqli code, you select a new row before each assignment so that the data is a combination of different field values ​​from different rows.

The correct way would look something like this:



// fetch the first row in the result set
$row = mysqli_fetch_assoc($sql);

$id_fabricante = $row['manufacturers_id'];
$cep_fabricante = $row['manufacturers_cep'];
$nome_fabricante = $row['manufacturers_name'];

      

Also, you will need to add error handling to make sure there is a line.

You should also avoid running sql queries in a loop. You could probably get all the rows in 1 query using for example mysql IN

, after which you can iterate over that result set.

+1


source







All Articles