PHP无法从数据库行获取单个值

时间:2014-04-08 06:03:47

标签: php mysql database select row

我试图从数据库行中获取单个值,但无论我使用什么,我什么也得不到。我试过了

$con=mysqli_connect("localhost","user","pass","db");
$product_cat = mysql_result(mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1  limit 1"),0);

$product_cat = mysql_fetch_assoc(mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1  limit 1"));

$product_cat = mysqli_fetch_field(mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1  limit 1"));

$product_cat = mysql_fetch_object(mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1  limit 1"));

$product_cat = mysql_fetch_row(mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1"));

但是当我回显$ product_cat时我什么也得不到(它应该回应1)。你能告诉我我做错了吗?

谢谢。

5 个答案:

答案 0 :(得分:0)

因为你正在混合mysqli_ *和mysql_ *函数,只能使用mysqli_ *函数

试试这个:

$product_cat = mysqli_fetch_row(mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1"));
echo $product_cat['product_category_id'];
print_r($product_cat);

答案 1 :(得分:0)

你的sql查询是否正确?

首先检查它,然后使用mysqli_fetch_row重试。

如果您还遇到问题,可以尝试使用mysqli_fetch_array,然后使用$result[0]这个字段。

否则,您可以使用print_r($result)打印结果以检查问题。

答案 2 :(得分:0)

试试这个

   $product_cat = mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1  limit 1");
   $row=mysqli_fetch_assoc($product_cat);
   echo $row["product_category_id"] ;

如果您要获取许多值,请使用以下命令:

  $product_cat = mysqli_query($con,"SELECT product_category_id FROM am_product_product_category WHERE product_id=1  limit 1");
   while ($row=mysqli_fetch_assoc($product_cat)){
       echo $row["product_category_id"] ."<br />";
       }

答案 3 :(得分:0)

请按照此示例。我认为此示例对您有所帮助。

$id = $_GET['id'];
$result = mysqli_query($con,"select *from employee_details where emp_id= '$id'  ");
echo "Emp-Id";
$row = mysqli_fetch_array($result)
  echo ". $row['emp_id'] . ";
mysqli_close($con);

                  (or)

也尝试这个

$product_cat = $mysqli->query("SELECT product_category_id FROM am_product_product_category WHERE product_id=1")->fetch_object()->product_category_id;

使用此代码。

答案 4 :(得分:0)

这是Programmer999提供的正确答案:

$product_cat = $con->query("SELECT product_category_id FROM am_product_product_category WHERE product_id=1")->fetch_object()->product_category_id;