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 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序