为什么sql查询不执行?

时间:2012-03-20 18:10:27

标签: php mysql pdo

此代码是我试图处理查询的代码,删除或插入没有影响。

id是正确的,conn.php是正确的。

我只是将sql查询复制到phpmyadmin进行测试,然后就可以了。

我在echo "test";之间放了一个try{}

谢谢

<?
include("../connection/conn.php");
session_start();

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// list out the pervious create list
//$id=$_GET['id'];

$id=3;
try{
$sql = 'INSERT INTO delete_list SELECT * FROM list WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="view.php"> Back</a>'); 
    }

try{
$sql = 'INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="view.php"> Back</a>'); 
    }

try{
$sql = 'INSERT INTO delete_require_attributes SELECT * FROM require_attributes WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="view.php"> Back</a>'); 
    }

try{
$sql = 'INSERT INTO delete_subscriber SELECT * FROM subscriber WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
$count=$stmt->rowCount();
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="view.php"> Back</a>'); 
    }

try{
$sql = 'INSERT INTO delete_list_sub SELECT * FROM list_sub WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="view.php"> Back</a>'); 
    }


    try{
$sql = 'DELETE FROM list WHERE ListID = ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
    {
    die ($e->getMessage().'<a href="view.php"> Back</a>'); 
    }

echo "The list has been deleted.".$count." subscribers has been removed. <a href='view.php'> Back</a>";

?>

我添加了

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

,错误是

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ListID' in 'where clause' Back

3 个答案:

答案 0 :(得分:2)

它不起作用,因为为了插入变量,你需要使用双引号(“)而不是单引号。单引号使它实际上传递”$ id“而不是值。

但是既然你正在使用PDO,你应该使用准备好的语句!像这样:

$sql = 'INSERT INTO delete_list SELECT * FROM list WHERE ListID=?'
$stmt = $conn->prepare($sql)
$stmt->execute(array($id));

$id的值取代?

编辑:修复参数

答案 1 :(得分:1)

在php中使用单引号可能是问题所在:

$sql = 'INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=$id';

这里,由于单引号“原始字符串”

,因此PHP解释器无法解析$ id

如果您想要解析$ id,请使用“(双引号)

$sql = "INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=$id";

或使用参数化语句(首选和更安全)

$sql = "INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=?";
$stmt = $conn->prepare($sql);
$stmt->execute($id);

答案 2 :(得分:0)

哪些查询未执行?你能检查一下是否有连接(这意味着你的凭证是否正确)?