将mysql_result转换为mysqli

时间:2015-07-11 05:56:32

标签: php mysql mysqli

我不是程序员,我知道PHP很少,但我正在尝试修复osCommerce商店中的代码,该代码在PHP 5.4上出现以下错误:

  

mysql_result():提供的参数不是有效的MySQL结果资源

这是代码:

$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;

    }

我尝试更改它并且没有更多错误,但它仍然无法正常工作。这是正确的方法吗?

$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;

}

1 个答案:

答案 0 :(得分:1)

不,这不正确。如果选中manual,您将看到第二个参数是结果集中要提取的行。在原始示例中,您只从第一行获取数据 - 0 - 而不是其他内容。

在你的mysqli代码中,你在每次赋值之前获取一个新行,这样数据就会混合不同行中不同字段的值。

正确的方法是:

// 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'];

除此之外,您还需要添加错误处理以确保有一行。

您还应该尝试避免在循环中运行SQL查询。您可以使用例如mysql&#39; s IN子句获取1个查询中的所有行,然后您可以遍历该结果集。