3

我需要制作一个 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() .'}}'; 
}


?>
4

3 回答 3

1

一个想法是创建一个包含 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 注入等。您可以阅读更多关于 PDO 的内容,这里有 nettuts 提供的非常容易理解的教程

希望这可以帮助你。

于 2012-04-17T12:22:37.120 回答
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!";
}
于 2012-04-17T10:39:30.367 回答
-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() .'}}';
}

?>
于 2012-04-17T12:03:07.290 回答