您好我正在尝试转换此代码
INSERT INTO destTable
SELECT Field1,Field2,Field3,...
FROM srcTable
WHERE NOT EXISTS(SELECT *
FROM destTable
WHERE (srcTable.ID=destTable.ID)
)
进入PHP查询。这是我到目前为止的错误。
mysql_query('INSERT INTO ' . $targetDB . 'SELECT * FROM' . $sourceDB . 'WHERE NOT EXISTS(SELECT * FROM' . $targetDB . 'WHERE ('. $targetDB . '`.` ID ='. $sourceDB . '`.` ID)'
你可以调整它以使其正确吗?
答案 0 :(得分:1)
您可以使用PDO和白名单数组尝试以下方法来验证表变量:
define('DB_HOST', 'localhost');
define('DB_NAME', 'your_database');
define('DB_USER', 'your_username');
define('DB_PASSWORD', '');
try {
//Make your connection handler to your database
$conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
$tables = array('table1', 'table2', 'table3');
if (in_array($targetDB, $tables) && in_array($sourceDB, $tables)) {
$sql = "INSERT INTO $targetDB (SELECT * FROM $sourceDB WHERE NOT EXISTS (SELECT * FROM $targetDB WHERE $targetDB.ID = $sourceDB.ID))";
$stmt = $conn->prepare($sql);
$stmt->execute();
} else {
echo 'Wrong tables';
}
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
答案 1 :(得分:1)
您只是遗漏了一些空间并添加了不必要的引号
'INSERT INTO ' . $targetDB . ' SELECT * FROM ' . $sourceDB . ' WHERE
NOT EXISTS(SELECT * FROM ' . $targetDB . ' WHERE ('. $targetDB . '.ID ='. $sourceDB . '.ID)'