我相信我的语法是正确的,至少根据我的教科书。这只是文件的一部分,因为其他信息与我的问题无关。表名是user,列名是user。我不相信这是问题,因为其他sql语句工作。虽然这不是最聪明的事情我知道:)任何人都看到错误?
try {
$db=new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user,$db_pass);
} catch (PDOException $e) {
exit("Error connecting to database: " . $e->getMessage());
}
$user=$_SESSION["user"];
$pickselect = "SELECT game1 FROM user WHERE user='$user' ";
$pickedyet = $db->prepare($pickselect);
$pickedyet->execute();
echo $pickselect;
if ($pickedyet == "0")
{
echo '<form method="post" action="makepicks.php">
<h2>Game 1</h2>......'
答案 0 :(得分:4)
由于您似乎正在使用预准备语句,我建议您最大限度地使用它们,以便您可以避免SQL注入等传统问题(这是当有人将恶意SQL代码传递给您的应用程序时,通过清理可以部分避免用户输入和/或使用绑定的预准备语句。
除此之外,您必须实际获取查询结果才能显示它们(假设这是您的目标)。 PHP有很好的文档和很好的例子。以下是一些链接:fetchAll; prepare; bindParam
以下是一个例子:
try
{
$db = new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user, $db_pass);
}
catch (PDOException $e)
{
exit('Error connecting to database: ' . $e->getMessage());
}
$user = $_SESSION['user'];
$pickedyet = $db->prepare('SELECT game1 FROM user WHERE user = :user');
/* Bind the parameter :user using bindParam - no need for quotes */
$pickedyet->bindParam(':user', $user);
$pickedyet->execute();
/* fetchAll used for example, you may want to just fetch one row (see fetch) */
$results = $pickedyet->fetchAll(PDO::FETCH_ASSOC);
/* Dump the $results variable, which should be a multi-dimensional array */
var_dump($results);
编辑 - 我还假设有一个名为'user'的表,其中一列名为'user',另一列名为'game1'(即你的SQL语句是正确的)绑定参数的用法。)
答案 1 :(得分:1)
<?php
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
try
{
// nothing was wrong here - using braces is better since it remove any confusion as to what the variable name is
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e ) // catch all exceptions here just in case
{
exit( "Error connecting to database: " . $e->getMessage() );
}
// this line is unecessary unless you're using it later.
//$user = $_SESSION["user"];
// no need for a new variable here, just send it directly to the prepare method
// $pickselect = '...';
// also, I changed it to a * to get the entire record.
$statement = $db->prepare( "SELECT * FROM user WHERE user=:user" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user', $_SESSION['user'], PDO::PARAM_STR );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );
echo $userRow->game1;
答案 2 :(得分:0)
使用此user=$user
更改此user='$user'
。请注意单引号。
此外,您正在执行查询$pickedyet->execute();
,但随后执行echo $pickselect;
,这与包含查询的字符串没有任何区别。
小提示: