dongxi7704 2017-07-10 19:45
浏览 59

sql UPDATE取决于行id

I'm trying to update the color value in the database through a form but is working only when I set the id, e.g.: WHERE ID=40"; but I need this to work with all the rows.

<?php

try
{
$bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8','root', '');
}
catch(Exception $e)
{
    die('Erreur : '.$e->getMessage());
}


$reponse = $bdd->query('SELECT id,pseudo, message, color  FROM 
minichat ORDER BY ID DESC LIMIT 0, 10');


while ($donnees = $reponse->fetch())
{
echo '<form action="minichat_post2.php" method="post">
    <table style="border:1px solid black">';
echo '<tr>';
echo '<td style="border:1px solid black">' .$donnees['id']. '</td>';
echo '<td style="border:1px solid black">' .$donnees['pseudo']. 
'</td>';
 echo '<td style="border:1px solid black">' .$donnees['message']. 
 '</td>';
  echo '<td style="border:1px solid black">' .$donnees['color']. 
 '</td>';
 echo '<td style="border:1px solid black">
 <label for="color">Color</label> :  <input type="color" name="color" 
 id="color" /><br />
    <input type="submit" value="Envoyer" />
    </td></tr></table>
      </form>';
 }
?>

$reponse->closeCursor();

?>

and this is the update page minichat_post2.php but is working uniquely when I set the id. So I need something to change here: WHERE id=?"; Please Help!!

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";


$id=$_GET['id'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE minichat SET color='".$_POST['color']."' WHERE id=?";

if ($conn->query($sql) === TRUE) {
 echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}


$conn->close();
header('Location: minichat.php');
?>
  • 写回答

1条回答 默认 最新

  • doulan1073 2017-07-10 19:50
    关注

    You need to add

      echo "<input type='hidden' name='id' value='".$donnees['id']."'>";
    

    into your first file (probably before the last echo). Then change $id = $_GET['id']; to $id = $_POST['id']; in the second file (as you are using method='post', not method='get'). And also in the second file change your query to:

    $sql = "UPDATE minichat SET color='".$_POST['color']."' WHERE id=".(int)$id;
    

    Please note that this code is susceptible to SQL injection attack. Using prepared queries may one way to mitigate.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看