Sjors Hijgenaar
Sjors Hijgenaar

Reputation: 1322

MySQL table not updating no errors

I have this little block of PHP code used to update a SQL table. However, it should, because right now it's not doing anything, nor is it producing any errors:

$sql = "INSERT INTO `wordpress`.`thor_members` ($key) VALUES('$_POST[$key]') WHERE ID = '$_POST[ID]'";
var_dump($sql);
mysqli_real_escape_string($conn, $sql);

if(mysqli_error($conn)){
    var_dump(mysqli_error($conn));
}

The var_dump actually prints MySQL lines that work perfectly fine if I run them into PHPMyAdmin.

Upvotes: 0

Views: 606

Answers (3)

Shaymol Bapary
Shaymol Bapary

Reputation: 458

$sql = "UPDATE `wordpress`.`thor_members` 
       SET ".$key."='".$_POST[$key]."' WHERE ID = '".$_POST["ID"]."' ";
mysqli_query($sql);

Try this way

Upvotes: 0

M. Eriksson
M. Eriksson

Reputation: 13645

$keyVal = mysqli_real_escape_string($conn, $_POST[$key]);
$id     = intval(mysqli_real_escape_string($conn, $_POST['ID']));
// I'm assuming $_POST['ID'] is an int?    

$sql    = "UPDATE `wordpress`.`thor_members` SET $key = '$keyVal' WHERE ID = $id";

mysqli_query($conn, $sql);

if(mysqli_error($conn)){
    var_dump(mysqli_error($conn));
}

This should work.

If $key comes from an unknown source, you should escape that too but id you set that in your own code before, this should be enough.

However, you should really look up prepared statements instead.

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33823

A variation on a theme.

<?php
    $sql = "INSERT INTO `wordpress`.`thor_members` ( `$key` ) VALUES ( '".mysqli_real_escape_string( $conn, $_POST[ $key ] )."' ) WHERE `ID` = '".mysqli_real_escape_string( $conn, $_POST['ID'])."'";
    var_dump( $sql );

    $result=mysqli_query( $conn, $sql );
    if( $result ){
        /* yeay - all good */

    } else {

        /* bogus */
        if( mysqli_error( $conn ) ){
            var_dump( mysqli_error( $conn ) );
        }   
    }
?>

Upvotes: 0

Related Questions