PHP update MYSQL Form not working - php

Im trying to edit the lastname (lname) but its not working ,
im getting this error :
ERROR: Could not able to execute UPDATE tablename SET fname = '',
lname = '' WHERE fname = . You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near '' at line 1
<?php
$link = mysqli_connect("IP","DB","PASS (hiden ofc)", "DBN");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE tablename SET fname = '$nfname', lname = '$nlname' WHERE fname = $fname";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
--- HTML CODE ---
<html>
<body>
<h1>Test editing </h1>
<form action="edit.php" method="post">
OrginalFirstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
NewFirstname: <input type="text" name="nfname" /><br><br>
<input type="submit" />
</form>
</body>
</html>

You forgot to put apostrophes on the last part of your query:
$sql = "UPDATE tablename SET fname = '$nfname', lname = '$nlname' WHERE fname = '$fname'";
This should work.
Make sure you escaped all the variables with mysqli_real_escape_string. If one of the variables has a non-escaped apostrophe, the query will fail again.
If the PHP code in your question is the entire code, then you are not getting the values from the $_POST[].
You can get the values into your variables using extract($_POST); on the beggining of your code.

Related

SQL Near error for inserting data through HTML form

I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.

By using php mysql create the table and retrieve the data,How to modify the data displayed in html?

I am new to the html and php, I had created the database in mysql by using the html and php,i had inserted values and retrieve the data from mysql to php,how can i modify the table means deleting the row,updating the row.
Below is my html code:
<html>
<head>
<title>STUDENT_DATA</title>
</head>
<body>
<form action="1.php" method="post" >
<center>
sname: <input type="text" name="sname" required><br></br>
sno:<input type="text" name="sno"><br></br>
marks:<input type="text" name="marks"><br></br>
class:<input type="text" name="class"><br></br>
phno:<input type="text" name="phno" onkeypress='return event.charCode >
= 48 && event.charCode <= 57'><br></br>
DOB:<input type="date" placeholder="DD-MM-YYYY"
required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}"
name="DOB"/><br></br>
<button>submit</button></br>
</center>
</form>
Below is my PHP code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$sname=$_POST['sname'];
$sno=$_POST['sno'];
$marks=$_POST['marks'];
$class=$_POST['class'];
$phno=$_POST['phno'];
$DOB=$_POST['DOB'];
if($sname!='' and $sno!='' and $marks!='')
{
$query = mysql_query("insert into hello1(sname, sno, marks, class, phno ,
DOB)
values ('$sname', '$sno', '$marks', '$class','$phno','$DOB')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else
{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
mysql_close($connection);
?>
Is there any one to help me?
Updation;
$query = "UPDATE hello1 SET column_name_1=value_1,column_2=value_2,... WHERE some_column=some_value;
$query = mysql_query($query);
Deletion
$query = "DELETE FROM hello1 WHERE some_column=some_value;
$query = mysql_query($query);
This is for ur comment :
take data from ur form, keep a unique constraint to use in where condition,
for example if the data u need to modify is "password" for username='admin', what u have to do is,
$query = "UPDATE hello1 SET password=$new_pw WHERE username=admin;
here $new_pasword should contain ur new pasword and username should be unique (if not, it will update all the rows with username as 'admin')
This is with reference to the code which u have sent to me.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
You cannot update like this because you haven't specified the required row(s) for updation.
for that what u have to do is just add a where condition.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
This means, u are updating name, adress and rollnumber of ur table venu, WHERE 'id' of
your row = 'the required one'
Hope this helps :)

PHP and sql issue

I have been trying to make my scoreboard system for some online game , It works correctly , So I have added an HTML form that interacts with a php script that connects to my sql database and inserts a name with a percentage into my sql scoreboard table , If I add the names/percentages manually via phpMyAdmin , It works perfectly on the scoreboard , But when I made the html form that asks the user to insert his name and then adds his name into the scoreboard with a percent , IT doesn't add , So here's my html form .
<center><form method="post" action="">
<font color="green">Your name Max length is 15</font> <input type="text" name="username" maxlength="15">
<button style="background-color:red; name="Enter" type="submit" value="HTML">Enter</button></center>
</form>
My PHP Form
<?php
if (isset($_POST['username']))
{
$getname = $_POST['username'];
$percentage = "10";
$link = mysqli_connect("myhost","myusername","mypw","mydatabase") or die("Error " . mysqli_error($link));
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
}
?>
Scoreboard is the name of my table , Columns are name/percent , Name accepts texts and Percent accepts Integers , Thanks in advance :) .
I tested your code and found that your submit button was one of the things at fault, including an improperly place semi-colon in:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');"
Which should read as:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage')";
Tested using the following form and PHP
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (isset($_POST['username']))
{
$link = mysqli_connect("myhost","myusername","mypw","mydatabase") or die("Error " . mysqli_error($link));
// $getname = $_POST['username'];
$getname = mysqli_real_escape_string($link,$_POST['username']);
$percentage = "10";
$query = ("INSERT INTO scoreboard (name,percent) VALUES ('$getname',$percentage)");
$result = mysqli_query($link, $query);
if(!$result){
printf("Error message: %s", mysqli_error($link));
}
else {
echo "Data properly inserted with the value of <b>$getname</b> and <b>$percentage</b>";
}
}
?>
NOTE: You will be better off using the code below in order to check if the field is empty. Otherwise, clicking on the submit button without anything inside, will produce an entry in DB with a blank name field.
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
// rest of code
Plus as stated by Hanky 웃 Panky, you should sanitize your variables like this, as done in my working example:
$getname = mysqli_real_escape_string($link,$_POST['username']);
Here is a safer (parametrized) method as taken from an example on SO here
Quick note: If you are going to use $percentage = 10; instead of $percentage = "10";
then you will need to use $stmt->bind_param("si", $unsafe_variable,$percentage); otherwise, your percentage will be treated as a string, as opposed to an integer and will be thrown an error. s is for string and i is for integer.
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
$mysqli = new mysqli("myhost","myusername","mypw","mydatabase");
// Check that connection was successful.
if($mysqli->connect_errno > 0) {
die('Connection failed [' . $mysqli->connect_error . ']');
}
$percentage = "10";
$unsafe_variable = $_POST["username"];
$stmt = $mysqli->prepare("INSERT INTO scoreboard (name,percent) VALUES (?,?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("ss", $unsafe_variable,$percentage);
$stmt->execute();
$stmt->close();
$mysqli->close();
echo "<div align='center'>Data written to DB</div>";
}
?>
Whenever in doubt about the correct usage of any function, take help from php.net first, it has so many examples on the pages about this. Have a look at
http://www.php.net/manual/en/mysqli.real-escape-string.php
http://php.net/mysqli_error
http://www.php.net/manual/en/mysqli.query.php
First sanitize your input value
$getname = mysqli_real_escape_string($link,$_POST['username']);
$percentage = 10;
Then
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname',$percentage)";
$result = mysqli_query($link, $query);
if(!$result){
printf("Error message: %s", mysqli_error($link));
}
This line needs fixed
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');" or die("Error in the consult.." . mysqli_error($link));
I've changed it to this
$query = "INSERT INTO scoreboard VALUES ('$getname','$percentage')";
then add or die("Error in the consult.." . mysqli_error($link)); to your query line.
You had a compiler line break in the middle of your variable and you don't need to state the order that your naming values, you just have to put the values in the correct places and it will automatically add them in order.

Insert into MySQL Table PHP

I am having some trouble making a simple form to insert data into a MySQL table. I keep getting this SQL error:
"Error: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'stock ('ItemNumber', 'Stock') VALUES ('#4','3'')' at line 1"
My HTML for the form is:
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit">
</form>
And the PHP is:
<?php
$con=mysqli_connect("localhost","root","root","inventory");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
try this
you should not use quotes of parameter around POST . and you should use them inside POST
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
you should escape your variables before you insert them to mysql like that
Note that the example does not call mysqli_real_escape_string. You would only need to use mysqli_real_escape_string if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.
You have an extra quote and you need ticks around your table name as it contains a space.
INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
should be:
INSERT INTO `current stock` (`ItemNumber`, `Stock`)
VALUES
('$_POST[ItemNumber]','$_POST[Stock]')";
FYI, you also wide open to SQL injections
?php
$conn=new mysqli("localhost","root","","inventory")
or die("not connected".mysqli_connect_error());
if(isset($_POST['submit']{
$ItemNumber=$_POST['ItemNumber'];
$Stock=$_POST['Stock'];
$sql="insert into current stock(ItemNumber,Stock) values('$ItemNumber','$Stock')";
$query=mysqli_query($conn,$sql);
if($query){
echo"1 row inserted";
}else{
echo mysqli_error($conn);
}
}
?>
Please learn to use parameter binding. You are creating code with security vulnerabilities.
Here's how to do your code in mysqli:
$sql = "INSERT INTO current stock (ItemNumber, Stock) VALUES (?, ?)";
if (!($stmt = mysqli_prepare($con, $sql))) {
die('Error: ' . mysqli_error($con));
}
if (!mysqli_stmt_bind_param($stmt, "ii", $_POST[ItemNumber], $_POST[Stock])) {
die('Error: ' . mysqli_stmt_error($stmt));
}
if (!mysqli_stmt_execute($stmt)) {
die('Error: ' . mysqli_stmt_error($stmt));
}
It's easier to use bound parameters than to get all confused with quotes-within-quotes.
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit" name="submit">
</form>`

Need assistance with a php mysql UPDATE statement tutorial please

Trying to follow a tutorial, but i get a database error on line six of the executable php file (second code below)
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_select_db("beyondmotors");//add your dbname
$sql = "select * from `TestTable` where ID = 1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['FName'];
$lname = $row['LName'];
$phone = $row['PHON'];
//we will echo these into the proper fields
}
mysql_free_result($query);
?>
<html>
<head>
<title>Edit User Info</title>
</head>
<body>
<form action="updateinfo.php" method="post">
userid:<br/>
<input type="text" value="<?php echo $id;?>" name="id" disabled/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $fname;?>" name="fname"/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $lname;?>" name="lname"/>
<br/>
Phone Number:<br/>
<input type="text" value="<?php echo $phone;?>" name="phon"/>
</br>
<input type="submit" value="submit changes"/>
</form>
</body>
</html>
and here is the executable
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_se lect_db("beyondmotors");//add your dbname
//get the variables we transmitted from the form
$id = $_POST[''];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = "UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',
`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
everything is good until i hit submit changes; than i get error on line 6. I'm new to database so please be specific if possible. Thank you! also if anyone could point me to a similar, "working" tutorial that would help ALOT!
trying to follow this tutorial: http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php
i'm using wamp server, so the database log in is correct. I mean it displays the data, just doesn't edit it..
The error i'm getting is :
Notice: Undefined index: ID in C:\wamp\www\test\updateinfo.php on line 6
i get that even if i change post to $id = $_POST['ID'];
Ok I changed the $_POST['']; to $_POST['id']; , still had the same error.
Than I read online to add a # to the front so now it looks like this: #$_POST['id'];
That too off all the errors. but not my data base is not been updated. Everything goes through with no errors but no data is been changed??
Also when i tried to remove backticks I get this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\test\updateinfo.php on line 12
So i left them the way they were...
Could it be because i'm using a local server? This should be all simple not sure what i'm doing wrong here.. I mean i literary copied everything over from the tutorial.
First and foremost, you should be warned that your code is completely vulnerable against sql injections. Escaping your POST data before inserting it into the database is a good start in protecting your database.
Also, learning the mysql extension is useless for new systems because it is deprecated. You might think about looking into the PDO interface or the mysqli extension. There are many beginner tutorials for both and you will gain much more.
Now, as for your error
Make sure you are defining which ID you want to update in your database. In your second block of code you have:
//get the variables we transmitted from the form
$id = $_POST[''];
needs to change to:
$id = $_POST['id'];
You said you get the error even if you change post to $id = $_POST['ID'], but if you look at your form, the id input has name = 'id' and PHP is case sensitive.
Now, in your sql query, all of those back ticks are unnecessary. Also, there is no point in specifying which table ID because this is all being done in ONE table, TestTable.
//replace TestTable with the name of your table
$sql = "UPDATE TestTable SET FName = '$fname',LName = '$lname',
PHON = '$phon' WHERE ID = '$id' LIMIT 1";
EDIT:
Although the query above is syntactically correct, you should consider using mysqli or PDO due to reasons mentioned above. Below are examples using mysqli and PDO.
Mysqli
mysqli Manual
/* connect to the database */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* build prepared statement */
$stmt = $mysqli->prepare("UPDATE TestTable SET FName=?, LName=?, PHON=? WHERE ID=?)");
/* bind your parameters */
$stmt->bind_param('sssi', $fname, $lname, $phon, $id);
/* execute prepared statement */
$stmt->execute();
/* close connection */
$stmt->close();
PDO
PDO Manual
/* connect to the database */
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
/* build prepared statement */
$stmt = $dbh->prepare("UPDATE TestTable SET FName = :fname, LName = :lname, PHON = :phon WHERE ID = :id");
/* bind your parameters */
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':phon', $phon);
$stmt->bindParam(':id', $id);
/* update one row */
$fname = 'John'; # or use your $_POST data
$lname = 'Doe';
$phon = '123-456-7890';
$id = 1;
/* execute prepared statement */
$stmt->execute();
/* use it again!1! */
$fname = 'Jane';
$lname = 'Doe';
$phon = '123-456-7890';
$id = 2;
/* execute prepared statement */
$stmt->execute();
/* close connection */
$dbh = null;
Remove backticks:
UPDATE TestTable SET FName = '$fname',LName = '$lname',PHON ='$phon'
WHERE TestTable.ID = '$id' LIMIT 1";

Categories