此代码不从学生表中获取数据

时间:2014-10-20 08:16:09

标签: php mysql

我有两张桌子,学生和stusub,
学生有snamesuni_roll_no
stusubsuni_roll_nosub_code 我请求sub_code,此代码不显示数据库的结果,

<?php
include("db.php");  

$sub_code =$_REQUEST['sub_code'];

$query = @mysql_query("SELECT student.sname, student.sroll_no
FROM student INNER JOIN stusub
ON student.suni_roll_no=stusub.suni_roll_no where sub_code  = '$sub_code';");
while($test = @mysql_fetch_array($query))
        {
            $sub_code = $test['sub_code'];  
            echo "<tr align='center'>"; 

            echo"<td><font color='black'>" .$test['sname']."</font></td>";
            echo"<td><font color='black'>" .$test['sroll_no']."</font></td>";


            echo "</tr>";
        }
        mysql_close($conn);
        ?>

3 个答案:

答案 0 :(得分:0)

试试这个。它使用PDO。请记住将数据库连接详细信息更改为您的

<?php

define('DB_TYPE', 'mysql');
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'dbname');
define('DB_USER', 'root');
define('DB_PASS', 'password');

try {
    // create a new instance of a PDO connection
    $db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    // if the connection fails, display an error message
    echo 'ERROR: ' . $e->getMessage();
}

$sub_code =$_REQUEST['sub_code'];

$sql = "SELECT student.sname, student.sroll_no FROM student LEFT JOIN stusub ON student.suni_roll_no = stusub.suni_roll_no WHERE stusub.sub_code  = :sub_code";

$stmt = $db->prepare($sql);
$stmt->bindValue(':sub_code', $sub_code);
$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row):
?>
<tr align="center"> 
    <td><font color='black'><?php echo $row['sname']; ?></font></td>
    <td><font color='black'><?php echo $row['sroll_no']; ?></font></td>
</tr>

答案 1 :(得分:0)

不应该放入查询;

try it

    <?php
    include("db.php");  

    $sub_code =$_REQUEST['sub_code'];

    $query =mysql_query("SELECT student.sname, student.sroll_no
    FROM student INNER JOIN stusub
    ON student.suni_roll_no=stusub.suni_roll_no where sub_code  = '$sub_code'");
    while($test =mysql_fetch_array($query))
            {
                $sub_code = $test['sub_code'];  
                echo "<tr align='center'>"; 

                echo"<td><font color='black'>" .$test['sname']."</font></td>";
                echo"<td><font color='black'>" .$test['sroll_no']."</font></td>";


                echo "</tr>";
            }
            mysql_close($conn);
            ?>

答案 2 :(得分:0)

尝试此查询

$ query = @mysql_query(“SELECT student.sname,student.sroll_no 来自学生INNER JOIN stusub ON student.suni_roll_no = stusub.suni_roll_no其中stusub.sub_code ='“。$ sub_code。”'“);

在where条件中使用tablename.sub_code。