PHP insert into not inserting any data - php

I have a php statement to insert a bit of information into my mySQL database. the connection works perfectly. The problem I am having is I am getting the following error code:
Error: INSERT INTO tasks ('taskName', 'requestedBy', 'details',
'dateAdded') VALUES ('test1' ,'test3' ,'test3', 2015-01-05') 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 ''taskName',
'requestedBy', 'details', 'dateAdded') VALUES ('test1' ,'test3' ,'te'
at line 1
the function is as follows
if(isset($_POST["submitTask"])){
insertTask();
};
function insertTask(){
$servername = "localhost";
$username = "tasktrack";
$password = "";
$dbname = "tasktrack";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$taskname = $_POST["task_name"];
$requestedby= $_POST["requested_by"];
$details = $_POST["details"];
$datenow = date("Y-m-d");
$sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
};
I have tried multiple different solution with the $sql line as seen below
$sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')";
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ($taskname ,$requestedb ,$details, $datenow)";
$sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES (`$taskname` ,`$requestedb` ,`$details`, `$datenow`)";
Now I am just stuck and can't think of any more things to try.

$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
// Removed quotes from columns, and added missing quote on datenow
Please note, this technique for adding values into the database is very insecure, and is prone to SQL injection attacks.

You must not enclose the field names in apostrophes or quotes. Either enclose them in back quotes (`) or use them as they are.
$sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
or
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
However, if the field name is a MySQL keyword or if it contains spaces, quotes, commas, parenthesis, operators or other characters that have special meaning in SQL then you have to enclose them in back quotes or MySQL will report a syntax error at the special character.

Related

Exporting a Line of Data From One Data Table to Another

The code below is for a project I'm working on. I'm having some issues with my PHP code and am in need of help.
I have a button on my data table named "Export". When the button is clicked, I wish to copy the data on that row and move it to an archive.
<?php
function val($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
$ticket_id = $_GET["ticket_id"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM activeticket WHERE ticket_id='$ticket_id' INSERT INTO `ticketarchive`(`name`, `account_num`, `department`, `ticket_desc`, `email`, `assigned`, `status`, `fibre_site`) VALUES ([name],[account_num],[department],[ticket_desc],[email],[assigned],[status],[fibre_site])";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully. Record ID is: ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Below is the error that this produces:
Error: SELECT * FROM activeticket WHERE ticket_id='1' INSERT INTO
archiveticket(name, account_num, department, ticket_desc,
email, assigned, status, fibre_site) VALUES
([name],[account_num],[department],[ticket_desc],[email],[assigned],[status],[fibre_site])
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 'INSERT INTO archiveticket(name, account_num, department,
ticket_desc, `' at line 1
First execute the select query and after that execute the insert one. Right now you are trying to run them both and this is the problem.
This isn't really a PHP issue you're having, you just seem to be unfamiliar with SQL.
What you're trying to do is insert the result of a SELECT query into a table. This isn't the way to do it at all.
What you're looking for is :
$sql = "INSERT INTO `ticketarchive`(
`name`,
`account_num`,
`department`,
`ticket_desc`,
`email`,
`assigned`,
`status`,
`fibre_site`
)
SELECT
`name`,
`account_num`,
`department`,
`ticket_desc`,
`email`,
`assigned`,
`status`,
`fibre_site`
FROM
`activeticket`
WHERE
`ticket_id` = $ticket_id"
For more information, read here.
I'd also advice you look into parametrized queries to avoid SQL injections.

SQLState 42000 syntax error. Possible table issue?

I'm stuck with a syntax error for a SQL query to insert data into a table.
Ah, the syntax error, most useless of all errors!!
Using the code modified from PHP Insert Data Into MySQL using both mysqli and PDO methods.
e.g.:
<?php
$servername = "localhost";
$username = "4w_write";
$password = "GjByhJzrQueHgTzw";
$dbname = "4w_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 4w (email) VALUES ($email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Having stripped it down to a single variable which isn't using a keyword, I'm pretty sure the problem is with my table.
SQL Query:
INSERT INTO 4w (email) VALUES (myemail#gmail.com)
Error:
Error: INSERT INTO 4w (email) VALUES (myemail#gmail.com) 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 '#gmail.com)'
at line 1
SQL table (4w):
# Name Type Default
1 id [Primary,Index] int(11)
2 email varchar(255)
3 whatIs tinytext
4 whereIs text
5 whattodo text
6 imageURL text
7 whenRep timestamp CURRENT_TIMESTAMP
The email value is a string, so you need to surround it with quotes:
$sql = "INSERT INTO 4w (email) VALUES ('$email')";
Or, better yet, use a prepared statement and bind it's value.
Couldn't see the problem, missing quotes....
Original code:
$sql = "INSERT INTO 4w (email) VALUES ($email)";
Fixed code:
$sql = "INSERT INTO 4w (email) VALUES ('$email')";

PHP inserting XML prices into SQL table - SQL syntax error [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I'm new on StackOverflow. Hope I'm doing the questioning correctly.
I'm trying to insert data from an external XML (URL) into an SQL table, but I get:
Error: INSERT INTO 'table_name' ('price')VALUE ('5.95')
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 ''BBB' ('price')VALUE ('5.95')' at line 1
I'm able to ECHO and PRINT values from the XML and also able to INSERT non-xml values into the table. The code I'm using is:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$xml=simplexml_load_file("external_xml_url") or die("Error: Cannot create object");
foreach ($xml->product as $row) {
$price = $row -> price;
$sql = "INSERT INTO 'table_name' ('price')"
. "VALUES ('$price')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Would be great if someone can help me out on this one. I've the feeling I'm pretty close...
As far as I know, with MariaDB you have to use Backticks to "qoute" an object's name.
Try it like this:
$sql = "INSERT INTO `table_name` (`price`) VALUES ('$price')";
If you do not deal with dangerous object names you might use just
$sql = "INSERT INTO table_name (price) VALUES ('$price')";
If you got your price properly then you should check your query
Ex.
INSERT INTO table_name (price) VALUES ('$price')

MYSQL database storing error [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Error: INSERT INTO grocery ('GrocerID', 'GrocerName', 'Address',
'LogoImage') VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh,
522124','WIN_20150817_121614.JPG') 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 ''GrocerID', 'GrocerName', 'Address',
'LogoImage') VALUES ('GID0072', 'BigBazaar' at line 1
<?php
$servername = "localhost";
$username = "root";
$password = "secret";
$dbname = "task";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$GrocerID=$_POST['GrocerID'];
$GrocerName=$_POST['GrocerName'] ;
$Address=$_POST['Address'];
$LogoImage=$_POST['LogoImage'] ;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO grocery ('GrocerID', 'GrocerName', 'Address', 'LogoImage')
VALUES ('$GrocerID', '$GrocerName','$Address','$LogoImage')";
if ($conn->query($sql) === TRUE) {
header('Location:task.html');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Data Base image
Can someone please tell me what the mistake I'm doing here??
I have used
database name: task,
table name: grocery
But i'm not able to understand where I'm doing the mistake.
Thankyou
not write coloumn in '' use backticks ``
INSERT INTO grocery
(GrocerID, GrocerName, Address, LogoImage)
VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh, 522124','WIN_20150817_121614.JPG')
Either Remove '
INSERT INTO grocery
(GrocerID, GrocerName, Address, LogoImage)
VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh, 522124','WIN_20150817_121614.JPG')
OR
Replace ' with ` (backtick)
[NOTE: You can find backtick below Esc key in keyboard]
INSERT INTO grocery
(`GrocerID`, `GrocerName`, `Address`, `LogoImage`)
VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh, 522124','WIN_20150817_121614.JPG')
And, Use real_escape_string() to prevent SQL Injection Attacks
PHP provides real_escape_string() to escape special characters in a
string before sending a query to MySQL. This function was adopted by
many to escape single quotes in strings and by the same occasion
prevent SQL injection attacks. However, it can create serious security
flaws when it is not used correctly.
$GrocerName = $conn->real_escape_string($_POST['GrocerName']);
$Address = $conn->real_escape_string($_POST['Address']);
$LogoImage = $conn->real_escape_string($_POST['LogoImage']);
$sql = "INSERT INTO grocery (`GrocerID`, `GrocerName`, `Address`, `LogoImage`)
VALUES ('$GrocerID', '$GrocerName','$Address','$LogoImage')";
Do not use quotes for column_name.

Inserting data into MySQL database

I'm struggling with inserting data from the form to database. I managed to establish the connection (at least not getting any errors), but when comes to inserting values I facing error, I'm not sure if rows/columns of the table should be in ' ' or not, I've seen some examples both with quotation marks and without, and also if variables should have those as well.
connecting to the database (connect.php):
<?php
define("DB_SERVER","localhost");
define("DB_USER","root");
define("DB_PASS","");
define("DB_NAME","Bookshop");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection){
die("error: unable to connect to database " . mysql_error());
}
$select_db = mysql_select_db(DB_NAME, $connection);
if(!$select_db){
die("error: unable to connect to database " . mysql_error());
}
?>
including connections:
<?php
include ("connect.php"); // connects to database
?>
and inserting data from the form:
$query = "INSERT INTO customer
(CUST_ID, CUST_NAME, CUST_SURNAME, HOUSE_NO, STREET, POSTCODE, PHONE_NO, EMAIL, OGIN, PASSWORD)
VALUES
('10101', '$forename', '$surname', '$address1', '$address2', '$postcode',
'$phone_no', '$email', '$login', '$password')";
mysql_query($query, $connection);
if(!mysql_query($query, $connection)){
echo "Error!!!!";
}
mysql_close($connection);
It seems you are a newbie.. Start with mysqli or pdo extensions. Visit W3schools.com for a detailed explanantion with examples. Below is an example of how to use mysqli to connect and insert a row in your database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
And For your query..
I'm not sure if rows/columns of the table should be in ' ' or not,
I've seen some examples both with quotation marks and without, and
also if variables should have those as well.
As far as insert queries are concerned,
1).Wrap up column names with ` back ticks.
2).Wrap your Variables with single quote nothing wrong in that
For more understanding about single and double quote usages,
Single quotes does not look for variables while double quote does
Case 1 :
$value = 10;
$sql = 'SELECT * FROM `table_name` WHERE `column_name` = $value';
echo $sql;
output is
SELECT * FROM `table_name` WHERE `column_name` = $value
Here if you see single quote does not look for a variable within it. Whatever there is inside single quotes, it is considered as a string and returned as such.
Case 2:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = $value";
echo $sql;
Output is
SELECT * FROM `table_name` WHERE `column_name` = 10
Here Since the query is inside double quotes, That variable is read. but considered as int.
Case 3:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = '$value'";
echo $sql;
Output is
SELECT * FROM `table_name` WHERE `column_name` = '10'
Here Since the query is inside double quotes, That variable is read. but considered as string as it is encapsulated with single quotes.

Categories