gpt4 book ai didi

php - MySQL 的 undefined variable 错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:53:06 25 4
gpt4 key购买 nike

我有一个数据库,其中包含 MyPrice、MyStock 等列。每个产品都有几行 - 苹果、桃子等。

我正在尝试使用以下代码提取有关多个项目的价格/库存状态的数据,但出现如下错误:

注意: undefined variable :第 11 行的 sql

警告:mysqli::query():第 11 行为空查询

注意: undefined variable :第 45 行的价格

注意:在第 45 行尝试获取非对象的属性

$dbhost =   'zzz';
$dbuser = 'zzz';
$dbpwd = 'zzz';
$dbname = 'zzz';

$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$res = $conn->query( $sql );

$item1 = "apple";
$item2 = "peach";

$items=array( $item1, $item2 );
$sql='select * from products where `Name` in ("'.implode('","',$items).'");'; //line 11

if( $res ){

$i=0;/* counter for dynamic variables */
$prices=new stdClass;

while( $rs=$res->fetch_object() ){
$i++;

/* Populate an object with details for the product */
$prices->{ strtolower( $rs->name ) }=(object)array( 'price'=>$rs->MyPrice, 'description'=>$rs->MyDescription, 'stock'=>$rs->MyStock );

}
}
?>

echo 'Apple:'.$prices->apple->price . '<br />'; //line 45
echo 'Peach:'.$prices->peach->stock . '<br />';

是什么导致了这些问题?

最佳答案

我已经根据你遇到的错误调试了你的代码。无论如何,消息应该引导你自己找到解决方案,特别是如果它们清晰明了。如果您总是让别人调试您的代码,您将学不到任何东西。

<?php

$dbhost = 'zzz';
$dbuser = 'zzz';
$dbpwd = 'zzz';
$dbname = 'zzz';

$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );


$item1 = "apple";
$item2 = "peach";

$items=array( $item1, $item2 );
$sql='select * from products where `Name` in ("'.implode('","',$items).'");';

// here's the first two errors.
// Notice: Undefined variable: sql on line 11
// Warning: mysqli::query(): Empty query on line 11
// You tried to query the db without defining $sql first (lines were mixed up) ->
$res = $conn->query( $sql );

if ($res) {
$prices=new stdClass();
$i=0; /* counter for dynamic variables */
while( $rs=$res->fetch_object() ){
$i++;

/* Populate an object with details for the product */
$prices->{ strtolower( $rs->name ) }=(object)array( 'price'=>$rs->MyPrice, 'description'=>$rs->MyDescription, 'stock'=>$rs->MyStock );

}
// here's 3rd and 4th error:
// Notice: Undefined variable: prices on line 45
// only output if you got values, so put the output into if-condition
echo 'Apple:'.$prices->apple->price . '<br />';
echo 'Peach:'.$prices->peach->stock . '<br />';
} else {
// database didn't return anything, so tell the user or something with that information.
echo 'no data found or an error occured<br />';
}
?>

关于php - MySQL 的 undefined variable 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34559844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com