简体   繁体   English

SELECT查询不适用于MySQL

[英]SELECT Query doesn't work MySQL

I can't seem to make my query work. 我似乎无法使我的查询正常工作。 When I use $sth->execute(); 当我使用$ 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];

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. PHP将在其中输出各种警告和错误,以帮助您进行调试,因此,如果您不知道该在哪里,那么现在就该找出答案了。

The technical fix is that query() is the wrong method to run on a statement handle. 技术解决方案是query()是在语句句柄上运行的错误方法。 Instead you call execute() : 相反,您调用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. 这是因为execute可以采用参数数组。

The order of arguments in SQL is conventionally column=? SQL中参数的顺序通常为column=? but you can do this in either order, MySQL's comparison is bi-directional. 但是您可以按任何顺序进行操作,MySQL的比较是双向的。 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 . 现在,具有诸如odds1team1类的列名称通常表明您违反了数据库规范化零,一或无限规则 A proper normal form would have a one-to-many relationship between one record and others. 适当的范式将在一条记录和其他记录之间具有一对多关系。

Change 更改

echo $values[odds1];

To

echo "<p>Results:<pre>".print_r($values[odds1],true)."</pre></p>\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM