I have two queries and I want to combine them into one so that it only returns one row in my database.
I have tried UNION but I keep getting an error. Can anyone please advise me on the code for it?
Below are my queries:
if(isset($_POST["response"]))
{
$query = "INSERT INTO response(response) VALUES (:response)";
$statement = $conn->prepare($query);
$statement->execute(
array(
':response' => $_POST["response"]
)
);
$query = " INSERT INTO response (student_id)
SELECT studentid
FROM student
WHERE studentid = '".$_SESSION['studentid']."'";
$statement = $conn->prepare($query);
$statement->execute(
);
UNION is used for combining multiple SELECT queries into a single result set. Check the mySQL (or any generic ANSI SQL) documentation.
Anyway, for no apparent reason you are making two INSERT queries when it looks like you're inserting into the same table and presumably want to insert everything into the same row in the same table. Right now you will make 2 rows instead of 1. You can insert more than one field as part of a single query.
I'm thinking:
if(isset($_POST["response"]))
{
$query = "INSERT INTO response (student_id, response) SELECT studentid, :response FROM student WHERE studentid = :studentID";
$statement = $conn->prepare($query);
$statement->execute(
array(
':response' => $_POST["response"],
':studentID' => $_SESSION['studentid']
)
);
}
However, since you only require the studentID in the table, and you already have the studentID from the session, it seems pointless to select from the students table at all. The only exception might be if you need to verify that the value in the session is correct - but surely you have already verified it before you added it to the session? If you haven't, you certainly should.
So in fact simply
if(isset($_POST["response"]))
{
$query = "INSERT INTO response (student_id, response) VALUES (:studentID, :response)";
$statement = $conn->prepare($query);
$statement->execute(
array(
':response' => $_POST["response"],
':studentID' => $_SESSION['studentid']
)
);
}
should be sufficient.
Is it possible to submit data to two tables with the same query?
My existing code looks like this:
private function adduser() {
if (!empty($this->error)) return false;
$params = array(
':user_level' => parent::getOption('default-level'),
':name' => $this->name,
':email' => $this->email,
':username' => $this->username,
':password' => parent::hashPassword($this->password)
);
parent::query("INSERT INTO `login_users` (`user_level`, `name`, `email`, `username`, `password`)
VALUES (:user_level, :name, :email, :username, :password);", $params);
I didn't write this code so it is a bit confusing to me as I don't usually use PDO. What I would like to do in addition to this is add two values to my 'url_alias' table, the first is the UID (which is auto incremented from the first query) and the second is another variable value.
All of the examples I have found while searching dont seem to work for me because of the way this existing code looks.
Can anyone give me a hand?
It doesn't matter what db driver your are using (PDO, Mysqli, etc.) you question is purely about mysql capabilities. Mysql may update and delete rows from multiple tables in a single query but not insert. I.e. INSERT table_1, table_2 ... is not allowed.
You have to run one query for each table you want to insert data.
So I am trying to change the status of something when values are met using WHERE
Code:
$insertstatus = $DBH->prepare("INSERT INTO
csvdata (status) VALUES ('$status') WHERE username = '".$username."'");
$insertstatus->execute();
Not working. If you could give me a hand.
Thank you for your time!
If you want to use the where clause, you need to use update. From the looks of it, you are trying to update anyhow as you are only using one column from your table.
$insertstatus = $DBH->prepare("update
csvdata set status= '$status' WHERE username = '".$username."'");
$insertstatus->execute();
As PeeHaa correctly points out though, using a prepared statement with parameters would be a slight change in your code, and a better option for you. You can do it like this:
$sql="update csvdata set status=:status where username=:username";
$sth=$DBH->prepare($sql);
$sth->execute(array(':status' => $status, ':username' => $username));
This way you are preparing the statement so the database knows what will happen. You then pass the variables to the database via the execute() function in an array.
I have 2 seperate databases with the same structure. I want to move a selected set of rows from one table to another. I am using PDO to select all the rows, then in a while loop I am assuming that I can insert each row into the new table then delete it from the old table.
With normal mysql this is quite a simple task, but I want to use namespaces so that I can easily modify the table structure ect. I have the following working but it does not move the entry to the new table:
try {
$sql = "SELECT * FROM `calls` WHERE `calls`.`status`=0 AND `calls`.`stage` < 4 AND `calls`.`answer` < (NOW() - INTERVAL 10 MINUTE)";
$query = $this->staging->query($sql);
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$sql = "INSERT INTO `table` (`field1`,`field2`) VALUES (?,?)";
$query = $this->production->prepare($sql);
$query->execute($array);
}
}
catch(PDOException $e) {
$this->informer("FATAL", "Unable to process broken IVR surveys. Error: ".$e->getMessage());
}
You can do it without a while:
INSERT INTO db1.table (fields) SELECT fields FROM db2.table
Of course both databases must be on the same machine
It likely does not work because you are using the question mark placeholder style in the prepared statement, but are passing a named array to execute.
If you name the parameters instead, it should work:
$sql = "INSERT INTO `table` (`field1`,`field2`) VALUES (:field1, :field2)";
Another approach is using federated tables in MySQL to do what you're trying to do. There are some limitations.... but here are the docs to get you going...
http://dev.mysql.com/doc/refman/5.0/en/federated-use.html http://dev.mysql.com/doc/refman/5.0/en/federated-limitations.html
my sql insert query is not working in my program. I have print the query and then copy paste that code in mysql tab of the phpmyadmin, then it works perfectly. Any body please help me.
if ($_FILES["thumbnailimage"]["size"]>0 )
{
$thumbnailkey = generateUniqueKey($tbl_uploads,"upload_key",12);
$fkey = generateUniqueKey($tbl_uploads,"file_key",24);
$folderkey = generateUniqueKey($tbl_uploads,"folderkey",28);
$fname = substr($_FILES['thumbnailimage']['name'],0,strpos($_FILES['thumbnailimage']['name'],"."));
$ext = getExtension($_FILES['thumbnailimage']['name']);
$insertnewupload = "INSERT INTO ".$tbl_uploads." (upload_key,file_key,file_name,file_type,ext,folderkey,user_id,status,pkey) VALUES ";
$insertnewupload.="('".$thumbnailkey."','".$fkey."','".$fname."','1','".$ext."','".$folderkey."','".$_SESSION['user_id']."','0','".$productkey."')";
echo "<br>1=>".$insertnewupload;
// $db->connect();
$exec_insertnewitem = mysql_query($insertnewupload);
This is the printed out put
INSERT INTO tbl_uploads (upload_key,file_key,file_name,file_type,ext,folderkey,user_id,status,pkey) VALUES ('f958c38e5c31','9b6bd5118ec4a8456bcc46df','sunil','1','jpg','1c1a536fbdde4f24a219ada4c1c9','7','0','3b593aff92ce')
You are quoting numeric values, you should aim for. I've added backticks around the field names also (I can't recall if 'status' is reserved)
INSERT INTO `tbl_uploads` (
`upload_key`,
`file_key`,
`file_name`,
`file_type`,
`ext`,
`folderkey`,
`user_id`,
`status`,
`pkey`
)
VALUES (
'f958c38e5c31',
'9b6bd5118ec4a8456bcc46df',
'sunil',
'1',
'jpg',
'1c1a536fbdde4f24a219ada4c1c9',
7,
0,
'3b593aff92ce'
)
So the following replacement for the line specifying values will suffice
$insertnewupload = "INSERT INTO `".$tbl_uploads."` (`upload_key`,`file_key`,`file_name`,`file_type`,`ext`,`folderkey`,`user_id`,`status`,`pkey`) VALUES ";
$insertnewupload.="('".$thumbnailkey."','".$fkey."','".$fname."','1','".$ext."','".$folderkey."',".$_SESSION['user_id'].",0,'".$productkey."')";
As an addition, there'll probably be a few comments stating you should be using mysqli_ functions or PDO instead of mysql_. At present you're potentially vulnerable to SQL injection with such a method of making a query.
Could be severy reasons... did you check that you connect to the correct database ? Maybe add the database name before "tbl_uploads", e.g. "mybase.tbl_uploads"
Always make practice to write mysql query like this.
$query = "INSERT INTO tablename (`upload_key`,`file_key`,`file_name`,`file_type`,`ext`,`folderkey`,`user_id`,`status,pkey`) VALUES ('f958c38e5c31','9b6bd5118ec4a8456bcc46df','sunil','1','jpg','1c1a536fbdde4f24a219ada4c1c9','7','0','3b593aff92ce')";
$check = mysql_query($query);
check if var_dump($check);returns true or false..