-2

another day another question...

I need to write PHP script to update mySQL database.

For example: updating profile page when user want to change their first name, last name or etc.

Here is my php script so far, it doesn't work. Please help!

<?php
@ $db = new MySQLi('localhost','root','','myDB');

if(mysqli_connect_errno()) {
    echo 'Connection to database failed:'.mysqli_connect_error();
    exit();
}

if (isset($_GET['id'])) {

$id = $db->real_escape_string($_GET['id']); 

$First_Name2 = $_POST['First_Name2'];

$query  = "UPDATE people SET $First_Name2 = First_Name WHERE `Id` = '$id'";

$result = $db->query($query);

if(! $result)
{
    die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";

$db->close();
}
?>

THank you.

user3457157
  • 47
  • 2
  • 9
  • What does "doesn't work" look like? Please provide more info so someone can help you. Messages would be helpful. I'm betting that the column name is First_Name, not $First_Name2. You can't bind column names. – duffymo Aug 15 '14 at 16:40
  • not really sure what you're asking. can you provide some things that you've tried? – iam-decoder Aug 15 '14 at 16:41
  • If only there were prior art on interfacing PHP with MySQL... In any case, what is the actual problem you're having? At what point doesn't it work? Have you tried copying an example you know works, and then gradually changing it until it doesn't? – Parthian Shot Aug 15 '14 at 16:41
  • The answer is working perfectly. Thank you all for responding. – user3457157 Aug 15 '14 at 16:57

1 Answers1

3

Your sql is wrong. Apart from the gaping wide open SQL injection attack vulnerability, you're generating bad sql.

e.g. consider submitting "Fred" as the first name:

$First_Name2 = "Fred";
$query = "UPDATE people SET Fred = First_name WHERE ....";

now you're telling the db to update a field name "Fred" to the value in the "First_Name" field. Your values must be quoted, and reversed:

$query = "UPDATE people SET First_name = '$First_Name2' ...";

You are also mixing the mysqli and mysql DB libraries like a drunk staggering down the street. PHP's db libraries and function/method calls are NOT interchangeable like that.

In short, this code is pure cargo-cult programming.

Marc B
  • 356,200
  • 43
  • 426
  • 500