正确的PHP语法

时间:2012-05-29 06:02:23

标签: php sql

// query
$sql = "INSERT INTO tool (title,details) VALUES (:title,:details) ";
$q = $conn->prepare($sql);
$q->execute(array(':details'=>$details,
                  ':title'=>$title));

整天都遇到麻烦,我终于明白了。如果我使用上面的代码,它只会向数据库添加一个新帖子。这应该用于编辑帖子,所以显然我需要编辑现有信息:

// query
$post = htmlspecialchars($_GET['story']);
$sql = "UPDATE  tool SET (title,details) VALUES (:title,:details) WHERE id = $post";
$q = $conn->prepare($sql);
$q->execute(array(':details'=>$details,
                  ':title'=>$title));

'id'是数据库中的一列。我需要它来更新该特定帖子的标题和详细信息。我只是不确定我应该在这里使用什么语法。

感谢您的回答!

=====第二个问题:

现在我回到原来的错误。每当我编辑帖子时,它都会丢失标题和详细信息,只会丢失一次。我第一次编辑帖子时,我丢失了所有信息,但剩下的时间它会正常工作。知道为什么吗?下面是代码:

来自编辑页面的表格(可能重要,也可能不重要,我不知道):

$name = $_SESSION['Username'];
if (in_array($name, $allowedposters)) {
$results = mysql_query("SELECT * FROM tool WHERE id = $post");
    while($row = mysql_fetch_array($results)){


$title= $row['title'];
$details= $row['details'];
$date= $row['date'];
$author= $row['author'];
$id= $row['id'];



echo "<a href=story.php?id=";
echo $post;
echo ">Cancel edit</a> <br><br><b>";
echo $title;
echo "</b> <br><br>";
echo '
<form action="edit-new.php?story=';
echo $id;
echo '" method="post" enctype="multipart/form-data">
<textarea rows="1" cols="60" name="title" wrap="physical" maxlength="100">';
echo $title;
echo '</textarea><br>';
?>



<textarea rows="30" cols="60" name="details" wrap="physical" maxlength="10000">
<?php 
echo $details;
echo '</textarea><br>';

echo '<label for="file">Upload featured image:</label><br>
      <input type="file" name="file" id="file" />';
echo'<br><input type="submit" />';
}

} else {
  echo "Not enough permissions.";
}
?>

这是SQL,插入DB:

<?php
   $post = htmlspecialchars($_GET['story']);
   $title = mysql_real_escape_string($_POST['title']);
   $details = mysql_real_escape_string($_POST['details']);
      echo "B<br>";
      echo $_POST['title'];
      echo '<br>';
      echo $_POST['details'];
      echo $post;
      echo "<br><br>";


// configuration
$dbtype     = "mysql";
$dbhost     = "localhost";
$dbname     = "zzzz";
$dbuser     = "zzzzz";
$dbpass     = "zzzzzz";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data


// query
$sql = "UPDATE  tool SET title=:title, details=:details WHERE id = :postid";
$q = $conn->prepare($sql);
$q->execute(array(
  ':details'=>$details,
  ':title'=>$title,
  ':postid' => $post
));




?>

1 个答案:

答案 0 :(得分:0)

修复您的sql UPDATE syntax

$sql = "UPDATE  tool SET title=:title, details=:details WHERE id = :postid";
$q = $conn->prepare($sql);
$q->execute(array(
  ':details'=>$details,
  ':title'=>$title,
  ':postid' => $post
));