我需要制作一个PHP代码,从服务器获取数据,更新数据以及将更新数据发送给用户的回声。我是PHP的初学者所以我不知道如何做到这一点。这是我现在拥有的代码。
那么如何更改代码以使其更新数据?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
答案 0 :(得分:0)
试试这个。我认为这与你所寻找的一致:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = @mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( @mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
答案 1 :(得分:0)
一个想法是创建一个由pdo连接组成的不同数据库连接文件,并在您的应用程序中重用它。如何做到这一点。
<{>>database.php
你可以像那样做
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
以及您想要使用的任何地方
require_once 'Database.php';
使用PDO的一些示例CRUD(创建,读取,更新,删除)是。
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
你还应该研究命名和未命名的占位符,以逃避SQL注入等。你可以通过nettuts here
阅读更多关于PDO的内容。希望这会对你有所帮助。
答案 2 :(得分:-1)
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>