drg5577 2014-11-19 20:01
浏览 26
已采纳

MySQL使用PHP查询

I cant seem to get this code to work. It keeps giving me the error "sorry: query failed". There is connection to the database cause if i input a wrong password it will give the error "mysql connection failed". The table pet is already created and populated with data. Please I need help

<?php
$conn = mysql_connect ("localhost", "vistor", "visitor", "test")
    or die ("sorry: Mysql connection failed");
$query = "select * from pet";
$result = mysql_query ($query,$conn)
    or die ("sorry: query failed");
while($row = mysql_fetch_array($result)) {
    echo $row['code'], " ", $row['name'];
    echo "<br>";
}
mysql_close($conn);
?>

Donny gave me the below code and i added some css to make it appear as a table but i am suspecting i have the coding wrong as I am getting errors. thanks

<html>
<head>
<title> php test script - hope this works </title>
</head>
<body>
<h1>php & mysql connection</h1>
<hr>
<?php
$db_host = "localhost";
$db_username = "vistor";
$db_pass = "visitor";
$db_name = "test";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $db->query('SELECT * FROM pet');
echo "<table border = '2'>"
<tr>
<th>id</th>
<th>name</th>
</tr>
while ($row = $query->fetch()) 
{
 echo "<tr>";
 echo "<td>" . $row['id'] ."</td>";
 echo "<td>" . $row['name'] . "</td>";
 echo "<td>" . $row['price'] . "</td>";
 echo "</tr>;
    }
echo "</table>";
?>
</body>
</html>
  • 写回答

2条回答 默认 最新

  • dongye9228 2014-11-19 20:36
    关注

    You should learn how to write the code in a prepared PDO statement. Since MySQL will be deprecated and writing it in MySQL can get you into trouble with injections. This is how you would write this code in a prepared PDO statement. You can write it in MySQLI, but the only thing is you would not be able to use your code with any other databases besides MySQL. With PDO you can use your code with any database like SQL, Access and more.

     <?php
        $db_host = "localhost";
        $db_username = "visitor";
        $db_pass = "visitor";
        $db_name = "test";
    
        $db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    
        $query = $db->query('SELECT * FROM pet');
    
        while ($row = $query->fetch()) {
         echo $row['code'], " ", $row['name'];
    
        }
        ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?