Mysql列没有返回正确的值

时间:2014-03-24 15:33:13

标签: php mysql loops foreach

我正在尝试从特定列中获取课程中剩余的位置数。但是,结果是返回 4 ,这是不正确的。它应该 15

以下是代码:

$courseID = $_GET['id'];

$result = mysql_query("SELECT * FROM course_dates WHERE id = '$courseID'");


$row = mysql_fetch_row($result);


foreach ($row as $record) {
    $placesLeft = $record['places'];
}


echo $placesLeft;

很明显,我是一个完整的菜鸟吗?

编辑:$ row的var_dump:

   array(7) { 
    [0]=> string(1) "2"
    [1]=> string(1) "2"
    [2]=> string(56) "Essential leadership and mangement skills in the new nhs"
    [3]=> string(6) "London"
    [4]=> string(10) "2012-12-15"
    [5]=> string(2) "15"
    [6]=> string(3) "450"
   } 

2 个答案:

答案 0 :(得分:1)

我相信您的ID是主要/唯一密钥

所以你只能得到一行作为结果集

所以使用:

$row['places']; 

足够不再重复它

答案 1 :(得分:1)

请尝试使用此方法:

使用$courseID = "1";并在其各自的列中生成1Place ONE以及Spain

1
放置一个 西班牙

<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";

$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
  die('Connection failed [' . $db->connect_error . ']');
}

// $courseID = $_GET['id'];
$courseID = "1"; // my own test. Column set to (INT)

$result = mysqli_query($db,"SELECT * FROM course_dates WHERE id = '$courseID'");

 while($row = $result->fetch_assoc()) {

    // my own example columns. Change to suit
    echo $row['id'];
    echo "<br>";
    echo $row['places'];
    echo "<br>";
    echo $row['city'];
}

mysqli_close($db);

使用$courseID = "2";并在其各自的列中生成2Place TWO以及LONDON

2
放置两个 伦敦