我试图在PHP的URL中传递多个变量来获取一些信息,但我认为这不起作用。
$allowedFunctions = array(
'returnAllProducts',
'refreshCurrentProduct'
);
$IDNUM = $_GET[ 'idNum' ];
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
$functionName();
}
然后我有refreshCurrentProduct函数:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
$query = "SELECT `ID` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
$DB_STOCK = mysql_query("SELECT `STOCK` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHORT = mysql_query("SELECT `MYNAME` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_LONG = mysql_query("SELECT `DESCRIPTION` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_PRICE = mysql_query("SELECT `PRICE` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHIP = mysql_query("SELECT `SHIPPING` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$ID = mysql_result($result,$IDNUM,"ID");
$STOCK = mysql_result($DB_STOCK,$IDNUM,"STOCK");
$SHORT = mysql_result($DB_SHORT,$IDNUM,"MYNAME");
$LONG = mysql_result($DB_LONG,$IDNUM,"DESCRIPTION");
$PRICE = mysql_result($DB_PRICE,$IDNUM,"PRICE");
$SHIP = mysql_result($DB_SHIP,$IDNUM,"SHIPPING");
echo '
//echo $STOCK, $SHORT, etc....
';
}
我使用的URL是
products.php?func=refreshCurrentProduct&idNum=4
理论上,它应该从包含4的行中显示,但是,它只显示第一行中的信息。如果我在函数中执行
$IDNUM=5
操作,它将显示第5行,因此我传递信息的方式有问题。另外,如何创建(例如)$STOCK而不必在$DB_STOCK中包含这么多代码?好像有更好的办法。。。
最佳答案
为什么不这样做(正如其他人已经提到的,$IDNUM
不在函数的范围内):
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$rowNumber = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS`";
$result = mysql_query($query);
if(mysql_data_seek($result, $rowNumber)) {
// The result set has indeed at least $rowNumber rows
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
else {
echo "No such row!";
}
}
不需要打六次数据库!当然,您需要添加错误处理。
顺便问一下,参数
idNum
是否与数据库中记录的ID
相同?如果是这样,您甚至可以进一步简化:function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$id = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS` WHERE ID = $id";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print";
return;
}
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}