Reputation: 21
i want to update my database using id
, I have already a database which have their name
Now when i update my database using WHERE college='1'
it works successfully but when i update my database using id
it's not working please help, and my database id=1
for which i'm working for..
here is my source code:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","members");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM admin");
while($row = mysqli_fetch_array($result))
{
echo "(".$row['id'].") ".$row['first_name']." ".$row['last_name'];
}
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora'
WHERE id='$id'");
mysqli_close($con);
?>
EDITED
after putting $id
it's showing an error undefined variable id.. what's that meaning?
Upvotes: 0
Views: 542
Reputation: 775
Define $id
and then something like this should work:
if ($stmt = mysqli_prepare($conn, "UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=?")) {
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
}
If $id
comes from a $_GET
or $_POST
variable, be sure to never embed it in a query directly!
Upvotes: 0
Reputation: 468
First your ID should be set and second your ID is probably not a string (varchar, char or text) in the database. It would be and should be numeric. In that the case, don't wrap the id in ''. Only string data should be wrapped in ''.
Upvotes: 1
Reputation: 1804
id
is a number, not a string. Change it to:
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=".$row['id']);
EDIT
Your id
is only used inside your loop. Try changing it from while
to if
$result = mysqli_query($con,"SELECT * FROM admin limit 0, 1");
if ($row = mysqli_fetch_array($result)) {
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=$row['id']");
}
Any other way, using while
, will change all user names in the table.
If you have more that one row in this table you'll need another approach.
Upvotes: 0
Reputation: 4830
$id
is not set in your code, referencing it will generate a warning and run the following query:
UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=''
You need to set $id
somewhere.
Also be aware of SQL injection depending on where this value is coming from, if it is from user input it needs to either be casted to an integer or escaped if it is a string.
If it is an integer you need not include quotes around it (WHERE id=1
as opposed to WHERE id='1'
).
Upvotes: 1
Reputation: 10896
try something like this,Remove single quotes
// Assign ID here
$id= 1;
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id='$id'");
Upvotes: 0