QUERY AND ECHO Data INTO HTML INPUT fields


QUERY AND ECHO Data INTO HTML INPUT fields

我编写了一个脚本,简而言之,该脚本应该从数据库中查询数据,并将结果回显到HTML表单字段中。然而,我一直没有成功。请参阅以下代码:

<?php

include("dbconfig.php");
$val = '6';
$result = mysqli_query("Select * from test where testid= '$val'");
$name = (mysqli_num_rows($result)==1) ? mysqli_fetch_assoc($result) : null;
if(is_array($name)){

?>
<html>
<body>
<form>
Name: <input type="text" id="firstname" value="<?php echo $name['firstname']; ?>"/>
</form>
<?php
} else {
echo "No such name exists";

}
?>

</body>
</html>

有人能告诉我我做错了什么吗。因为它不会在领域中产生任何反响,我觉得这很烦人,因为我遇到的大多数脚本都与此脚本非常相似。

我们将不胜感激。

谢谢你,

Sohail。

我已经测试了下面的内容,它运行正常。@Fred ii-给了你很多好的信息,尤其是使用错误调试-但你确实需要提供你丢失的连接对象。

<?php
    error_reporting( E_ALL );
    include("conn.php");
    $val = 6;
    /* What is the name of the $connection object ? */
    $result = mysqli_query( $conn, "Select * from `test` where `testid`='$val'" );
    $name=( $result ) ? mysqli_fetch_assoc( $result ) : false;
?>  
<html>
    <head>
        <title>Ya gotta have a title...</title>
    </head>
    <body>
        <?php
            if( !empty( $name ) ){
                echo "
                    <form>
                        Name: <input type='text' id='firstname' value='{$name['firstname']}'/>
                    </form>";
            } else {
                echo "No such name exists";
            }
        ?>
    </

您没有将数据库连接传递给查询,因此它永远不会被执行。

  • 假设使用mysqli_成功连接

这行代码:

$result = mysqli_query("Select * from test where testid= '$val'");

需要有一个连接参数:

$result = mysqli_query($connection, "Select * from test where testid= '$val'");

并且我们不知道您使用哪个MySQL API来连接。

您的查询可能已失败,请检查是否有错误。

$result = mysqli_query("Select * from test where testid= '$val'")
    or die(mysqli_error($connection));

并将$connection变量替换为您在dbconfig.php中分配的变量,这对我们来说是未知的

不同的MySQL API/函数不会混用。

请参阅以下链接http://php.net/manual/en/mysqli.error.php和http://php.net/manual/en/function.error-reporting.php并将其应用于您的代码。

您还可以接受SQL注入。使用事先准备好的语句。

  • https://en.wikipedia.org/wiki/Prepared_statement

参考文献:

  • http://php.net/manual/en/mysqli.query.php
  • http://php.net/manual/en/function.mysqli-connect.php

错误报告添加到文件顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code

旁注:显示错误只能在暂存中进行,而不能在生产中进行。


如果你想检查是否存在一行,请参阅我在Stack:上的另一个答案

  • https://stackoverflow.com/a/22253579/1415724