-1

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');
?>
scunja
  • 37
  • 6
  • 1
    Use `bind_param()` to bind variables to the placeholder `?` – Jay Blanchard Jul 10 '17 at 19:47
  • 1
    You're using placeholders `?`, so you need to use [`mysqli::prepare()`](http://php.net/mysqli.prepare) and [`mysqli_stmt::bind_param()`](http://php.net/mysqli-stmt.bind-param). – Qirel Jul 10 '17 at 19:47
  • Possible duplicate of [How to run the bind\_param() statement in PHP?](https://stackoverflow.com/questions/15748254/how-to-run-the-bind-param-statement-in-php) – GrumpyCrouton Jul 10 '17 at 19:53

1 Answers1

0

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.

Martin
  • 22,212
  • 11
  • 70
  • 132
Jirka Hrazdil
  • 3,983
  • 1
  • 14
  • 17