2012-04-17 171 views
2

我需要制作一个PHP代码,从服务器获取数据,更新数据并向用户更新数据。我是PHP的初学者,所以我不知道如何做到这一点。这是我现在拥有的代码。从数据库中选择数据并进行更新PHP/PDO

那么如何更改代码以使其更新数据?

<?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

是否要选择或更新?你的sql查询是用于select的。 – 2012-04-17 10:29:04

+0

我想选择数据然后更新它。更新查询是在评论中,但我不知道在哪里以及如何把它。 – user1323294 2012-04-17 10:33:03

+0

你想更新什么?你为什么要用相同的值更新你的数据库? – Bono 2012-04-17 10:39:27

回答

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!"; 
} 
+0

我需要json_encode更新的查询。我怎样才能做到这一点? – user1323294 2012-04-17 10:49:17

+0

你为什么用@来抑制错误。可能是一个坏主意-1 – 2012-04-17 12:10:11

+0

,你也看不到他在使用PDO。你向他展示了错误的方向 – 2012-04-17 12:11:16

-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() .'}}'; 
} 

?> 
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';

和一些样品CRUD(创建,读取,更新,删除)使用PDO。

//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理解教程here

希望这可以帮助你。