1

I have a simple script that should Update variable in a column where user login equals some login.

<?PHP
$login = $_POST['login'];
$column= $_POST['column'];
$number = $_POST['number'];

$link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test");

$ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'");
if ($ins)
    die ("TRUE");
else
    die ("FALSE");
?>

but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?

4 Answers 4

4

Simply remove quotes: '$column' = should be $column =


Your code is open for SQL Injection, use prepared statements.

Sign up to request clarification or add additional context in comments.

Comments

1

change this "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"

to this "UPDATE test_table SET '".$column."' = ".$number." WHERE log = '".$login."'"

Comments

0

It's possible that your error is to do with the $column being set as a string with single quotation marks? Because it returns false, it suggests that you have a MySQL error of some sort.

To find out what the error message is, on your else block, rather than dying with a "FALSE" message, try use mysqli_error($link) - this should give you your error message

1 Comment

There is no error in SQL, just returned 0 updated rows, because 'string' != 'another_string'.
0

If removing the quotes surrounding the $column doesn't work, you could try the PDO method. Here's the snippet:

function insertUser($column, $number, $login) {
try 
{ 
    $connect = getConnection(); //db connection
    $sql = "UPDATE test_table SET $column = '$number' WHERE log = '$login'";
    $connect->exec($sql); 
    $connect = null; 
 } catch (Exception $ex) { 
     echo "EXCEPTION : Insert failed : " . $ex->getMessage(); 
 } 
 }

function getConnection() { 
 $servername = "localhost"; 
 $dbname = "my_db"; 
 $username = "root"; 
 $password = "12345"; 

 try { 
     $connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 
     $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
 } catch (Exception $ex) { 
     echo "EXCEPTION: Connection failed : " . $ex->getMessage(); 
 } 

     return $connection; 
 } 

Regarding $number, I'm not sure the datatype for the $number whether quotes or not is needed so experiment with or without quotes to see which one works.

And the getConnection() function is in separate PHP file where it will be included in any PHP files that calls for database connection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.