Insert into MySQL Table PHP - 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>`

Related

Database error when inserting values into MySql

I have an error on insert value mysql.
Please see my PHP code
<?php
$ali = $_POST['ali'];
$con = #mysqli_connect('localhost', 'root', '', 'mohammad');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
$insertinto_ic_add = "INSERT INTO sq (text) VALUES ('" . $ali . "')";
mysqli_query($con, $insertinto_ic_add) or die("database error:" . mysqli_error($con));
?>
<form action="" method="post">
<input name="ali">
</form>
I input the values " n't " and an error occurs:
database error:You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 't')' at line 2
I agree that this is not showing SQL injection. But the prevention for such is the same as the fix for your problem. You must escape certain characters (in particular the apostrophe) in the text.
Notice that the error message even points to the apostrophe.
If you echoed the statement, you would see
INSERT INTO sq (text)
VALUES ('blah blah don't do this')
Observe the three apostrophes, and think how confused the parser will be.
Better code would be something like
$mali = $con->real_escape_string($ali);
$insertinto_ic_add = "INSERT INTO sq (text)
VALUES ('" . $mali . "')";

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.

PHP update MYSQL Form not working

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.

PHP SQL update multiple rows at once

I am stuck in a very crucial part of my project and would like some help - however I seem to be stuck in the PHP / SQL syntax and cannot get the query to work.
HTML code:
<form name="homepage" method="POST" action="" >
<p>Page Title</p>
<input id="pagetitle" type="text" name="home_title" value="<?php select_text("SELECT fieldcontent FROM content WHERE name='home_title'", "fieldcontent") ?>"/>
<p>Paragraph</p>
<textarea id="paragraph" name="home_text"><?php select_text("SELECT fieldcontent FROM content WHERE name='home_text'", "fieldcontent") ?> </textarea>
<h1>Images</h1>
<div id="image">
<?php select_image("SELECT * FROM `image` WHERE image_cat_id = 8"); ?>
</div>
<button name="homesavebtn" id="home-save-btn" type="submit">Save Updates</button>
</form>
PHP code - Select data
function select_text($sql, $echo) {
include 'connect.php';
$result = $conn->query($sql);
if ($result->num_rows > 0);
while ($row = $result->fetch_assoc()) {
echo $row[$echo];
$conn->close();
}
}
PHP code - update
if ($_POST) {
if (isset($_POST['homesavebtn'])){
$home_title = (isset($_POST['home_title']) ? $_POST['home_title'] : null);
$home_text = (isset($_POST['home_text']) ? $_POST['home_text'] : null);
include 'connect.php';
$sql = "INSERT INTO content(name, fieldcontent) VALUES ('home_title', '$home_title') ON DUPLICATE KEY UPDATE fieldcontent = '$home_title'";
$sql .= "INSERT INTO content(name, fieldcontent) VALUES ('home_text', '$home_text') ON DUPLICATE KEY UPDATE fieldcontent = '$home_text'";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "" . $sql . "<br>" .mysqli_error($conn);
}
$conn->close();
}
}
Getting the following error:
INSERT INTO content(name, fieldcontent) VALUES ('home_title', 'Mosta Cycling Club') ON DUPLICATE KEY UPDATE fieldcontent = 'Mosta Cycling Club'INSERT INTO content(name, fieldcontent) VALUES ('home_text', '') ON DUPLICATE KEY UPDATE fieldcontent = ''
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 'INSERT INTO content(name, fieldcontent) VALUES ('home_text', '') ON DUPLICATE KE' at line 1
You could use VALUES to get the new value you are using in the update portion. Also, if you use prepare and bind_param you will prevent SQL injection:
$mysqli = new mysqli('host', 'user', 'password', 'db');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO content(name, fieldcontent)
VALUES ('home_title', ?), ('home_text', ?)
ON DUPLICATE KEY UPDATE fieldcontent = VALUES(fieldcontent)");
$stmt->bind_param('ss', $home_title, $home_text);
$stmt->execute();
Your second SQL statement is being added to your first creating one long statement that doesn't make sense. Separate these into two different statements.

PHP Insert Command not working

Hi guys can you please tell me if there is an error on this code. this is not working. it didn't add any on my database. thanks you!
$con = mysql_connect("localhost","root","pass");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mytable",$con);
if(isset($_POST['add'])){
// Variables
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";
mysql_query($AddQuery, $con);
echo "Record Successfully Added!!";
};
mysql_close($con);
?>
<form action="add.php" method="post">
Account Classification:
<input required="required" placeholder="e.g Hotel, Restaurant" type="text" name='acc_class' size=15 />
<input type="submit" name='add' Value=' Add Record '/>
</form>
The column name(s) should be wrapped in backticks and not quotes
$AddQuery = "INSERT INTO mytable (`acc_class`) VALUES ('$acc_class')";
or remove the quotes
$AddQuery = "INSERT INTO mytable (acc_class) VALUES ('$acc_class')";
I suggest you move to mysqli_* functions with prepared statements or PDO.
and that you change $acc_class = $_POST['acc_class']; to
$acc_class = mysql_real_escape_string($_POST['acc_class']);
for the time being.
mysql_* functions are deprecated and will be removed from future PHP releases.
At a minimum:
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";
Should be:
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('".$acc_class."')";
Also, it is unsafe to pass raw user input into to a SQL query in this way. Please read up on SQL Injection.

Categories