Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

PHP script to update mySQL database

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
";

$db->close();
}
?>

THank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...