【发布时间】:2015-11-19 11:14:52
【问题描述】:
我有一个会话,其中包含一个数组,每个数组都有键和值。在数组设置并存储在会话中之后,我想从 mysql 表中获取并回显所有信息,其中数组的 $key 为 = 到我的表中的 id。
我正在使用 foreach 循环来回显每个数组的每个 $key 和 $value,但我想回显 mysql 表中的数据,它也等于每个键。
我的桌子
id | name | animalheight |
-------------------------------------------------------
2012dog dog 1m
2022cat cat 0.3m
所以我想回显名称和动物高度,如果会话密钥已设置并且等于表的 id。
给出错误的代码部分
///////////////DUMPING EVERYTHING FROM DATABASE////////////////////////////////////
$sql = "select * from products where $key =$id";
$myData = mysql_query($sql,$con);
if($record = mysql_fetch_array($myData))
{
echo "<br/>";
echo "||||||||||||||||". $row['name']. "||||||||||||||||";
echo "<br/>";
}
/////////////////////DUMPING EVERYTHING FROM DATABASE/////////////////////////////////////
我的完整代码
//code
<?php
//////////////////////////////////////////////
$con = mysql_connect("localhost","****","");
mysql_select_db("*********",$con);
//////////////////////////////////////////////
session_start();
// create an array
$my_array=array( '2012dog' => 1 , '2022cat' => 2);
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
$aaa = $_POST['aaa'][$i];
$key_var = $_POST['ke'][$i];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
}
?>
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
////////////////////////////DUMPING EVERYTHING FROM DATABASE////////////////////////////////////////////////
$sql = "select * from products where $key =$id";
$myData = mysql_query($sql,$con);
if($record = mysql_fetch_array($myData))
{
echo "<br/>";
echo "||||||||||||||||". $row['name']. "||||||||||||||||";
echo "<br/>";
}
////////////////////////////DUMPING EVERYTHING FROM DATABASE////////////////////////////////////////////////
// and print out the values
echo "Product ID is " .$key. " Quantity is ";
// getting the updated value from input box
?>
<input type="text" name="aaa[]" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke[]" value="<?php echo $key; ?>"><br>
<?php
}
?>
<input type="submit" value="Update value of key" name="submit"/>
</form>
提前致谢!
【问题讨论】:
-
我厌倦了 $key='key';..... 然后说 select where key = $id 但没用 ;s
-
未定义变量:id 和 mysql_fetch_array() 期望参数 1 是资源,布尔值在
-
这里有 6 打错误,但是
id ='$key'键是一个字符串,所以它需要引号,循环是个坏主意,mysql_* 是个坏主意 -
一切正常,但//////////////////////////////////////////////////////////////////////////////////////////// 部分
-
您感到困惑吗?你写了那个可憎的东西。