doupi1532 2014-04-20 14:48
浏览 186
已采纳

PHP:连接到数据库,但mysql_query失败

I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.

This is my source where I have this problem:

<?php
    // Here I open connection
    $con = mysql_connect("localhost","root","aaaaaa");
    // set the mysql database
    $db = mysql_select_db("infs", $con);

    // I check the connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else {
        // It always goes here
        echo "Connected to database!";
    }

    // I am testing very simple SQL query.. there should be no problem
    $result = mysql_query("SELECT * FROM cathegories", $con, $db);

    if (!$result) {
        // but it always dies
        $message  = 'Invalid query: ' . mysql_error() . "
";
        $message .= 'Whole query: ' . $query;
        die($message);
    }

    mysql_close($con);
?>

What is wrong?

Thanks in advance!

  • 写回答

3条回答 默认 最新

  • dqj29136 2014-04-20 15:03
    关注

    You are mixing mysql and mysqli. Try something like:

    <?php   
        $con= new mysqli("localhost","user","passwd","database");
        if ($con->connect_errno){
          echo "could not connect";
        }
    
        $select = "SELECT * FROM tablename";
    
        if($result = $con->query($select)){
            while($row = $result->fetch_object()){
                echo $row->rowname."<br>";
            }
        }
        else { echo 'no result'; }
        $con->close();  
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置