我有一个包含数组的会话,其中键和值分配给每个数组。在数组设置并存储在会话中之后,我想从mysql表中获取并回显所有信息,其中数组的$ key是=到我表中的id。
我正在使用foreach循环来回显每个$ key和每个数组的$ value,但是我想回显mysql表中的数据,它等于每个键。
我的表
id | name | animalheight |
-------------------------------------------------------
2012dog dog 1m
2022cat cat 0.3m
所以如果设置会话密钥并且等于表的id,我想回显名称和animalheight。
出现错误的代码部分
///////////////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>
感谢提前!
答案 0 :(得分:1)
你可以做这样的事情,
// First get all the keys
$key_array = array_keys($_SESSION['animals']);
// Get all records
$sql = "select * from products";
$myData = mysql_query($sql,$con);
// Loop through each record and see if $row['id'] is present in the $key_array or not
while($row = mysql_fetch_array($myData)){
if(in_array($row['id'], $key_array)){
// display records
}
}