-5

I am new in PHP. I want to update a MySQL table using variables.

$sql = "UPDATE tableName 
           SET $variable1='$variable2' 
        WHERE table_no='$variable3'";

Thanks

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149

1 Answers1

0

Don't use mysqli_. Use PDO.

If you HAVE to use mysqli_, use a prepared statement:

 $mysqli = new mysqli("localhost", "my_user", "my_password", "world");
 $smth = $mysqli->prepare('UPDATE tableName SET '.$variable1.'=? WHERE table_no=?');

 $smth->bind_param($variable2, $variable3);

That should do it, though I didn't run it. I encourage you to use PDO, though:

$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$query = $conn->prepare('UPDATE tableName SET '.$variable1.'=A WHERE table_no=B');
$query->bindParam('A', $variable2);
$query->bindParam('B', $variable3);

EDIT

Updated the mysqli section to use proper bind_param syntax.

Zac Brown
  • 459
  • 4
  • 12
  • That isn't my downvote that you got, but it seems you may have gotten it because of this `$smth->bindParam($variable2, $variable3);` which is PDO syntax and not `mysqli_`. And the missing quote `('UPDATE tableName SET '.$variable1.'=? WHERE table_no=?)` – Funk Forty Niner Oct 01 '15 at 12:18
  • 1
    The syntax for `mysqli_` is `bind_param()` http://php.net/manual/en/mysqli-stmt.bind-param.php and not `bindParam()` http://php.net/manual/en/pdostatement.bindparam.php – Funk Forty Niner Oct 01 '15 at 12:25
  • @Fred-ii-, you're totally right. Updated answer so I don't look like such an idiot anymore :) – Zac Brown Aug 02 '16 at 15:56
  • That's great Zac. As you can see now, I've upvoted it, yet your answer now has a `0` which was "neutralized". OP however, is nowhere to be found. – Funk Forty Niner Aug 02 '16 at 15:58