doutun9179 2018-05-28 15:58
浏览 32
已采纳

SELECT Query不适用于MySQL

I can't seem to make my query work. When I use $sth->execute(); I do get a reading, yet is pretty worthless for my goal as far as I know. If I use query, nothing shows up. Keep in mind that I'm a beginner when it comes to coding. Also, this is a school project and nothing more.

I don't know why the first line of code won't be implemented so look at the row below as part of the code:

$team1 = $_POST['teamname'];
$sth = $pdo->prepare("SELECT odds1 FROM odds WHERE :team1=team1");
$sth->bindParam(':team1', $team1);
$sth->query();
$values = $sth->fetchAll(PDO::FETCH_ASSOC);                 
echo $values[odds1];
  • 写回答

2条回答 默认 最新

  • dswe30290 2018-05-28 16:05
    关注

    This code should be crashing with errors, so if you're wondering why it "doesn't work" the first place to check is your error log. PHP will output all kinds of warnings and errors there that help with your debugging, so if you don't know where that is now's the time to find out.

    The technical fix is that query() is the wrong method to run on a statement handle. Instead you call execute():

    $sth = $pdo->prepare("SELECT odds1 FROM odds WHERE :team1=team1");
    $sth->bindParam(':team1', $team1);
    $sth->execute();
    

    You can actually minimize this:

    $sth = $pdo->prepare("SELECT odds1 FROM odds WHERE :team1=team1");
    $sth->execute([ ':team1' => $team1 ]);
    

    This is because execute can take an array of parameters.

    The order of arguments in SQL is conventionally column=? but you can do this in either order, MySQL's comparison is bi-directional. It'll make your code more conventional if you write your query as:

    $sth = $pdo->prepare("SELECT odds1 FROM odds WHERE team1=:team1");
    

    Now having a column name like odds1 and team1 is usually a sign that you've violated the Zero, One or Infinity Rule of database normalization. A proper normal form would have a one-to-many relationship between one record and others.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥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更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了