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
,
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 INTOarchiveticket
(name
,account_num
,department
,
ticket_desc
, `’ at line 1
2
Answers
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 :
For more information, read here.
I’d also advice you look into parametrized queries to avoid SQL injections.