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.
Related
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')";
So im trying to get my data from my form submission to be put into a mysql database but whenever i submit a form it gives me this error: Error: INSERT INTO form_submissions(ID, first, last, phone, class) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])
Now here is my PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_database";
$value = $_POST['first'];
$value1 = $_POST['last'];
$value2 = $_POST['phone'];
$value3 = $_POST['class'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])";
if ($conn->query($sql) === TRUE) {
echo "Submitted Successfully";
} else {``
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
assuming that ID is auto-incrementing, and that the others are text,
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,
`class`) VALUES ('$value','$value1','$value2','$value3')";
Your query should be like:
INSERT INTO `form_submissions`(`first`, `last`, `phone`, `class`)
VALUES ('John','doe', '98564', 'SOMECLASS');
To check: echo the $sql query and debug it in phpmyadmin.
Note: If you enabled AUTO_INCREMENT, you can ignore the data feed of that column. It will do its job automatic.
Security tip - >
To prevent SQLi Injection check out this post.
There are two things wrong.
The first thing is you give 5 fields (ID, First, last, phone, class)
And you only have 4 variables in your post. I think you don’t need to send the ID on an insert if the column is set to auto increment in the database, So don’t send an value for the ID field.
Your variables are not correctly inserted in the query.
The [value-1] douse not mean the $value1 variable will automatically be injected in there.
This can be done in a lot of way’s
I wil give you a simple solution, (but it wil be a bad one for real websites). The simple solution is:
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,`class`) VALUES (`$value`,`$value1`,`$value2`, `$value3`)";
The reason this is bad is: You are directly entering post data inside your query and are now vounerable to SQL-Injections. You need to escape your post data befoure inserting it in a query. Or better yet don’t use ‘mysqli’ but an PDO.
An good PDO example can be found here
https://www.w3schools.com/php/php_mysql_insert.asp
I hope this helps.
Your SQL is apparently wrong. It should look's like with something like that:
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ($value1,$value2,$value3,$value4,$value5)";
The field ID should be auto_increment. If it is, you don't need to pass value to it.
I have been developing a website on localhost with xampp and everything worked perfect. so i moved to a web host for the first time. I have edited my connection string to fit the web server and it connects fine but when i tried testing the registration page i designed it doesn't insert data into the database. I tried a simple insert statement on a separate script
<!DOCTYPE html>
<html>
<body>
<?php
$conn = mysql_connect("localhost", "my_db_user_name", "my_db_password");
$db = mysql_select_db("my_db_name");
$query1 = mysql_query("INSERT INTO users firstname VALUES 'Patrick'",$conn);
if($query1) {
echo "Yes";
} else {
echo "didn't work";
}
echo mysql_error($query1);
?>
</body>
</html>
It returned the didn't work and didn't insert anything neither did it echo any error. But when i tried a select statement and echo the result of the query it worked so its safe to say my connection is valid.
I also went to my cpanel phpmyadmin interface and tried the same insert statement it didn't work but returned:
1064 - 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 'firstname VALUES 'Patrick'' at line 1.
I tried with and without back ticks the same thing. but i can select query.
You missed the correct syntax for the insert.
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example from w3schools:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_insert.asp
Your query needs to look like this
INSERT INTO (columns) VALUES (values)
So you will get
INSERT INTO users (firstname) VALUES ('Patrick');
Dude... one second google, and you would have your answer.
http://www.w3schools.com/sql/sql_insert.asp
Also, the error says there is a SYNTAX ERROR. It is so difficult to understand? Why you don't simply check your syntax?
INSERT INTO users (firstname) VALUES ('Patrick')
Hello i have a problem with my query ill keep getting errors from my query
this is my error;
Error: BEGIN; INSERT INTO our_work (id) VALUES ('6'); INSERT INTO
our_work_portf_img (portf_id, img_id) VALUES ('6', '7'); INSERT
INTO our_work_images (img_id, image) VALUES ('7', 'adawd.jpg');
COMMIT; 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 our_work (id) VALUES ('6'); INSERT INTO `our_wo'
at line 3
i've tried many things but i noticed one thing if i copy the $query string and i posted the query directly in mysql the problem will not accorded and it works just how i hoped it would.
Does anyone noticed the problem in my query cause im literal out of ideas.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit_new_img'])){
$pjt_dtls = $_POST['project_details'];
$categories = $_POST['categories'];
$link = $_POST['link'];
$image_path = "adawd.jpg";//$_POST['file']; //$_POST['image'];
$row_id ='6';//++$num_rows['i'];
$image_id ='7'; //++$num_rows['ii'];
$sql = "
BEGIN;
INSERT INTO `our_work`
(`id`)
VALUES
('{$row_id}');
INSERT INTO `our_work_portf_img`
(`portf_id`, `img_id`)
VALUES
('{$row_id}', '{$image_id}');
INSERT INTO `our_work_images`
(`img_id`, `image`)
VALUES
('{$image_id}', '{$image_path}');
COMMIT;
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
$conn->query($sql) does not work with multi-query like yours
you need to use multi_query instead
also here is nice comment:
Please note that there is no need for the semicolon after the last
query. That wasted more than hour of my time...
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.