PHP MYSQL update stament not working - php

This code is meant to check the submitted form values and update the table,
however it just replaces the field with a blank
Any ideas where it is gone wrong, please?
<form action = "update.php" method = "POST">
<p>
New Name: <input type "text" name="name">
<input type= "submit">
</p>
</form>
<?php
require ('/var/www/html/site1/connect_db.php');
if(!empty($_POST['name']) && !is_numeric($_POST['name']))
{
$name=$_POST['name'];
$name=mysqli_real_escape_string($dbc,$query);
$name=strip_tags($name);
#$query='update customers SET customerName = '".$name."' where customerNumber=114';
$query = "update customers ". "SET customerName = $name"."where customerNumber=114" ;
mysqli_query($dbc,$query);
}
else
{
echo $name;
}
$query = 'select * from customers where customerNumber=103';
$result = mysqli_query($dbc,$query);
while ($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
echo"<p>Name : $row[1]</p>";
}
mysqli_close($dbc);
?>

You are updating customer number 114 but selecting 103 out, whose name may be blank.
Your update statement needs to have quotes around the $name bit as below:
$query = "UPDATE customers SET customerName = '$name' WHERE customerNumber=114";
Edit: please see the parameterised query advice in the question comments.

Related

Increment ID by getting the last record id from mysqli table

I am trying to get the last Employee ID from my Sqli table, increment the id retrieved from the table and insert the new value into the table along with the new record.
The code is not working as the table is not getting updated.
<form method="POST">
<input type="text" name="brn" placeholder="Branch"/>
<input type="text" name="nam" placeholder="Enter Name"/>
<input type="submit" name="insert">
<?php
$db=mysqli_connect("localhost","root","","test");
session_start();
if(isset($_POST['insert']))
{
$brn = $_POST['brn'];
$nam = $_POST['nam'];
$qry = "SELECT * FROM emp";
$result=mysqli_query($db,$qry);
$row = mysqli_fetch_array($result);
$empid= $row["empid"];
$empid++;
$query = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
mysqli_query($db,$query);
mysqli_close($db);
}
?>
</form>
You need some changes in your code.
You are selecting the first "EmpId" instead of the last one and if you are having the column empid as primary key, it will show the error of primary key violation.
Therefore change your query to somewhat this:
$qry = "SELECT * FROM emp order by empid desc limit 1";
It will return one row.
And, if you just need the last empid then i would suggest you to go with only:
$qry = "SELECT empid FROM emp order by empid limit 1";
This is more resource effective query.
****Happy Coding.****
you can try this. I hope it will help you.
$sql = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
if(mysqli_query($db, $sql)){
$last_id = mysqli_insert_id($db);
echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

How to update through foreach loop

I want to update data of form fields in database through foreach loop. I have two columns in test_table ID and Input. I have fetched data through while loop and also have printed the value. Now I want to update fetched value. Please give some guidance for this.
Here is my code,
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql))
{
while($row = mysqli_fetch_array($result))
{
$inputResult[]=$row;
}
} <form method="POST"> <input type="text" value=<?php
echo $inputResult[0]['Input']; ?> id="$inputResult[0]['ID']"> <input
type="submit" name="submit"> </form> <?php
if (isset($_POST['submit'])
{
$input = $inputResult[];
foreach($input as $inputs => $value)
{
$Sql = "update test_table set Input='$value' where = '$inputs'";
mysqli_query($conn, $sql);
}
} ?>
Please let me know what errors have in my code ? Thanks in advance.
Next solution is very specific to your problem. The input text is the first element in your form, so, in the PHP code, we can get the input's ID and the VALUE by accessing the first item in the array $_POST (changes are pointed by arrows ◄■■■):
<?php
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql)) {
while($row = mysqli_fetch_array($result)) {
$inputResult[]=$row;
}
}
?>
<form method="POST">
<input type="text" value="<?php echo $inputResult[0]['Input'];?>"
name="<?php echo $inputResult[0]['ID'];?>" /> ◄■■■ NAME, NOT ID.
<input type="submit" name="submit" />
</form>
<?php
if ( isset($_POST['submit']) ) {
$value = reset( $_POST ); // ◄■■■ FIRST VALUE IN $_POST (['input']).
$id = key( $_POST ); // ◄■■■ FIRST KEY IN $_POST (['ID']).
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
}
?>
I replaced the attribute id= by name= in the input text, because PHP needs names, not ids.
After we get the first value and the first key, we can insert them into the sql string.
Edit :
Fixed the missing tags (oops!). I think I found the error, it's so little that it's hard to see : pay attention to next line:
▼
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
Do you see the variable on the left : $Sql (the first letter is uppercased). Now let's see the next line:
▼
mysqli_query($conn, $sql);
The same variable is not uppercased, once you fix that, everything works :
▼
$sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
▲

PHP - Mysql Query

I have a problem regarding my correct script for query..
I created a form in page1.php where the user have to input the fname, mname, and lname.
page1.php
<form action = "page2.php" method="post" target="<?php $_SERVER['PHP_SELF']?>">
First Name:<input type="text" name="fname"/>
Middle Name:<input type="text" name="mname"/>
Last Name:<input class = "type="text" name="lname"/>
<input type="submit" name="submit" value="NEXT" />
</form>
The entries are sent to page2.php to be inserted into the database. After successful process. I placed a condition after a successful insertion of the values, it automatically goes to page3.php.
page2.php
<?php
include('config.php');
if(isset($_POST['submit']))
{
$fname = ucwords(strtolower($_POST['fname']));
$lname = ucwords(strtolower($_POST['lname']));
$mname = ucwords(strtolower($_POST['mname']));
$submit=$_POST['submit'];
if(empty($fname) || empty($lname) || empty($mname))
{
echo '<b>Please fill out the form completely.</b>';
}
else
{
$dup = mysql_query("SELECT *
FROM
tbl
WHERE
fname = '$fname'
AND
lname = '$lname'
AND
mname = '$mname'
");
if(mysql_num_rows($dup) >0)
{
echo "<br/>";
echo '<b>Already Registered.</b>';
echo "<br/>";
}
else
{
$sql = mysql_query("INSERT INTO tbl(fname,lname,mname) VALUES('$fname','$lname','$mname')");
if($sql)
{
echo "<br/>";
echo "You have successfully added your new name!";
echo "<br/>";
header("Location: page3.php?fname= $fname&mname= $mname &lname= $lname");
}
else
{
echo "Error Registration";
header("Location: index.php");
}
}
}
}
?>
The values will also be carried over by the:
header("Location: page3.php?fname= $fname&mname= $mname &lname= $lname");
which is placed right after the:
$sql = mysql_query("INSERT INTO tbl(fname,lname,mname)VALUES('$fname','$lname','$mname')");
Then goes to next page.
In page3.php, in order to verify that I still have the values I used:
echo '<pre>' . print_r($_GET,true) . '</pre>';
And I still have them.
Now, in page3.php I want to call the auto_incremented ID that was created after the successful insertion of the values from page2.php.
<?php
echo '<pre>' . print_r($_GET,true) . '</pre>';
include('config.php');
$fname = $_GET['fname'];
$mname = $_GET['mname'];
$lname = $_GET['lname'];
$sql = mysql_query("SELECT * FROM tbl WHERE fname = '$fname' AND mname = '$mname' AND lname = '$lname'");
while ($row = mysql_fetch_array($sql))
{
echo $row['id'];
}
?>
Now, the problem is that their no results coming out from my query. When I try this is script:
$sql = mysql_query("SELECT * FROM tbl");
I have results showing up.
What I want to do is this, I want the conditions to be fulfilled altogether namely the fname, mname, lname. The 3 fields must be satisfied so that I can get the specified ID from the table which has those fields specifically. Its like you have the query your fullname and get the ID for you. You should insert all 3 fields in order to get the exact ID for that given name.
My problem probably lies here:
$sql = mysql_query("SELECT * FROM tbl WHERE fname = '$fname' AND mname = '$mname' AND lname = '$lname'");
while ($row = mysql_fetch_array($sql))
{
echo $row['id'];
}
It's like you to have John Rogers Smith then find out your ID from the database.
Can you help me? I dont understand why it's not working.
Tnx guys in advance.
Please check every stap you do, because the form already has an error
Last Name:<input class = "type="text" name="lname"/>
needs to be
Last Name:<input class="" type="text" name="lname"/>
and the way you do the querys is not secure, its easy to do sql injection.
Also i would suggest you to use sprintf(), example:
$s_query = sprintf("SELECT * FROM `x` WHERE `x`.`x_name` = '%s'", $x_name);
And you should go for mysqli instead of mysql.
Next time always print out every stap, use print_r() to print arrays like $_GET and $_POST
may i ask to all it may work without give error or warning
echo "Error Registration";
header("Location: index.php");

PHP/HTML Form not updating MySQL

I can't seem to find a solution to this and i've looked for similar threads too but no luck
Basically here's my code, when you click Update it's meant to display your current name in the form fields then you can overwrite them and submit the changes, however sadly it will not update, it only displays the originally set first name and last name and does not update the database so therefore not displaying the new set names.
<?php
include('../connect_db.php');
$res = mysqli_query($dbconnection, "SELECT * FROM users");
$row = mysqli_fetch_array($res);
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
$newFirst = $_POST['newFirst'];
$newLast = $_POST['newLast'];
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id='$id'";
$res = mysqli_query($dbconnection, $sql);
}
?>
<div id="editSection">
<h3>Edit Details</h3>
<form action="edit_profile.php" method="POST">
<input type="hidden" value="<?php echo $row[0];?>" name="id"/>
<h2>First Name</h2>
<input type="text" name="newFirst" value="<?php echo $row[1];?>">
<h2>Last Name</h2>
<input type="text" name="newLast" value="<?php echo $row[2];?>">
<input type="submit" value="Update">
</form>
</div>
Any help would be greatly appreciated :)
Kind Regards
~ Matt
You have to connect to DB before updating.so use
$con=mysqli_connect("localhost","my_user","my_password","my_db");
There are several other errors like you have to make $POST['newFirst'] as $_POST['newFirst'] like this
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
And change the query to
$sql = "UPDATE users SET first_name='$newFirst',last_name='$newLast' WHERE id= '$id'";
beacuse you have error at end of query id='first_name='$id' which is wrong
I see some error in the query
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id='first_name='$id'";
should be
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id= '$id'";
also
if(isset($POST['newFirst']) && isset($POST['newLast'])){
should be
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
You are using $POST wrong in your if-condition.
It must be called $_POST[..].
Also you should take a look at your WHERE in your update query.
I think you mean: WHERE id= '$id'
You should get your id from $_POST['id']; which is your row ID i suppose and also the update query must be where id=$id.
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id=$id";
Also have you checked in DB after the update? the row[0], row[1], row[2] used will have old set of values used during select before the update happened. can you have the mysqli_fetch_array($res) after the update call?

MySQL update doesn't work

I want to update 2 of my database's fields according to user input.My code is something like this:
<body>
<?php
$db_server["host"] = "localhost"; //database server
$db_server["username"] = "root"; // DB username
$db_server["password"] = "mypass"; // DB password
$db_server["database"] = "mudb";// database name
$dbc = mysql_connect($db_server["host"], $db_server["username"], $db_server["password"]);
mysql_select_db($db_server["database"], $dbc);
$user = $_COOKIE['mycookie'];
$q = "SELECT * FROM members WHERE username='$user'";
$r = mysql_query( $q,$dbc);
while ($row = mysql_fetch_array($r, MYSQLI_ASSOC)) {
echo 'username: '.$row['username'], '<br/>';
$password=$row['password'];
?>
<form method="post" id="changepasswordform" >
<input type="password" id="newpassword" name="newpassword"/>
<input type="submit" name="changepasswordbutton" >
</form>
<?php
echo 'email: '.$row['email'], '<br/>';
}
?>
<form method="post" id="changeemailform" >
<input type="text" id="newemail" name="newemail"/>
<input type="submit" value="αλλαγή" name="changeemailbutton" >
</form>
<?php
}
if (isset($_POST['changepasswordbutton'])){
$newpassword=$_POST['newpassword'];
$q2 = "UPDATE members SET password=$newpassword WHERE username='$user'";
$r2 = mysql_query($q2,$dbc);
}
if (isset($_POST['changeemailbutton'])){
$newemail=$_POST['newemail'];
$q3 = "UPDATE members SET email=$newemail WHERE username='$user'";
$r3 = #mysql_query( $q3,$dbc);
}
?>
</body>
However although my connection to my db is ok(SELECT displays results as expected) when i try to UPDATE , the values inside my db remain the same.I checked the values of $newpassword and $newemail and they do contain the user inputs each time.What am i missing here?
You're missing the '' (quotes) that supposed to surround the password field.
change:
UPDATE members SET password=$newpassword WHERE username='$user'
to:
UPDATE members SET password='{mysql_real_escape_string($password)}'
WHERE username='{mysql_real_escape_string($user)}'
IMPORTANT:
And even though it's not related, please don't use mysql_* functions - it's deprecated and vulnerable to sql-injection. Better use PDO or MySQLi.
This will do the trick and is save for sql injection (mysql_real_escape_string):
$q2 = "UPDATE members SET
password='". mysql_real_escape_string($password) ."'
WHERE username='". mysql_real_escape_string($user) ."';
But off course you shouldn't use mysql_* anymore, I'm just giving an example for your specific case.

Categories