如何使用php检查数据是否插入MySQL

时间:2014-01-19 17:29:36

标签: php mysql

这是我的代码

我正在从Mysql数据库中搜索并希望显示消息,如果记录找到状态为FOUND,如果找不到记录显示FOUND ??

<?php
    $status="";
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {   
        $degree=$_POST["degree"];
        $mysql_host = "*******";
        $mysql_database = "**********";
        $mysql_user = "*******";
        $mysql_password = "*********";

        $conn = mysql_connect($mysql_host, $mysql_user, $mysql_password);
        if(!$conn )
        {
            die('Could not connect: ' . mysql_error());
        }

        mysql_select_db($mysql_database)or die("cannot select DB");
        $sql = "SELECT *
            FROM studentRecord
            WHERE degree='$degree'";
        $result=mysql_query($sql,$conn);
        if(!$result )
        {
            $status="not found";
        }
        else
        {
            while($row = mysql_fetch_array($result))
            {    
                echo  $row['name'];echo "<br>";
                echo  $row['degree'];
                echo "<br>";
            }
            $status="";
        }
        echo "<h1>" . $status . "</h1>";    
    }
?>

这是我的表格

<h1>Search</h1>
<form action="search.php" method="post">
    <div class="form_settings">
        <p>
            <select name="degree">
                <option></option>
                <option>Civil Engineering</option>
                <option>Urban & Infrastructure Engineering</option>
                <option>Petroleum Engineering</option>
                <option>Mechanical Engineering</option>
                <option>Textile Engineering</option>
                <option>Industrial & Manufacturing Engineering</option>
                <option>Automotive & Marine Engineering</option>
                <option>Electrical Engineering</option>
                <option>Computer & Information Systems Engineering</option>
                <option>Electronic Engineering</option>
                <option>Chemical Engineering</option>
                <option>Materials Engineering</option>
                <option>Metallurgical Engineering</option>
                <option>Polymer & Petrochemical Engineering</option>
                <option>Software Engineering</option>
                <option>Construction Engineering</option>
                <option>Computer Science & Information Technology</option>
            </select>
            <span style="float:right;"class="error">
        </p>
        <br>
        <input class="submit" type="submit" name="searchSubmit" value="SEARCH" />  
    </div>    
</form>

我正在从Mysql数据库中搜索并希望显示消息,如果记录找到状态为FOUND,如果找不到记录显示FOUND ??

1 个答案:

答案 0 :(得分:2)

使用mysql_num_rows()

$result = mysql_query($sql, $conn) or die( mysql_error() );

if( mysql_num_rows($result) <= 0 )
    echo 'not found';
else
    echo 'found';

<强> PS。不推荐使用mysql_ *,使用mysqli_ *或pdo