duan0417 2014-12-04 09:34
浏览 46
已采纳

在Heroku上使用php访问clearDB数据库时查询错误

I can access clearDB database well by using Mysql Workbench.

But when I query database by using php on Heroku, it always fail.

This is my code:

$url=parse_url(getenv("CLEARDB_DATABASE_URL"));

$dbhost = $url["host"];
$dbuser = $url["user"];
$dbpass = $url["pass"];
$dbname = substr($url["path"],1);

mysqli_connect($dbhost, $dbuser, $dbpass);

mysqli_select_db($dbname);

$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$user_account."'";

$result = mysqli_query($sql) or die('MySQL query error');

user_account is a table in the database, $user_account is a input variable from client user

help me thanks

  • 写回答

1条回答 默认 最新

  • dpowt82802 2014-12-05 14:48
    关注

    You're not passing the link to mysqli_query(). You need to either do that, or use the object oriented style and call query() on the connection.

    You also have a possible SQL injection there, because $user_account could contain "foo' OR 1 OR '", returning all rows (and that's just a simple, not very evil case), so you should escape that using mysqli_real_escape_string(), or even better, use prepared statements.

    Finally, instead of or die(), how about extracting error information properly, or even configuring mysqli to throw exceptions?

    <?php
    $url = parse_url(getenv("CLEARDB_DATABASE_URL"));
    
    $server = $url["host"];
    $username = $url["user"];
    $password = $url["pass"];
    $db = substr($url["path"], 1);
    
    $conn = new mysqli($server, $username, $password, $db);
    
    $sql = "SELECT * FROM `user_info` WHERE `user_account`='".$conn->real_escape_string($user_account)."'";
    
    if($result = $conn->query($sql)) {
        foreach($result as $row) {
            // ...
        }
    } else {
        throw new Exception($conn->error);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码