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.
I'm trying to upload data to a existing User database I have stored online. I need to post the user phone number string in the user specified row. Using android and php, is there any way to post extra info in an existing row?
I think I'm not choosing WHERE to put that extra info.
<?php
require "indioPhP.php";
$username = $_POST["username"];
$phoneNumber = $_POST["phoneNumber"];
$statement = mysqli_prepare($con, "SELECT * FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
$sql ="insert into User values('$phoneNumber')";
if(mysqli_query($con,$sql)){
echo "Gracias por registrarte!";
} else{
echo "error in insertion".mysqli_error($con);
}
?>
Ok now i see your Problem:
Update User set phonenumber=? where username=?
You Need something like this ? it's only one query where you search the user and Change it. Try to read more about SQL. Your code Looks a bit confused, with prepared Statements and normal statments in the same block.
Edit:
The statement insert adds a new line in the table wheras update modifies an existing one. Assuming your table User has 4 columns: username, firstname, lastname, phonenumber, for insert, the syntax is either
insert into user values("jdoe", "John", "Doe", "555 7565")
or
insert into user(username, phonenumber) values ("jdoe", "555 7565")
In the first case, as columns are not specified, you must give all of them.
In the second case, you insert a new line specifying only some columns. The other ones will take their default values. If a missing column doesn't have a default value, you will have an error.
...i am not getting any further.
my database contains a column 'name' = 'John Richards'
i try to query it like:
$act = "John Richards";
prepareEditing($act);
function prepareEditing($act) {
include ($_SERVER['DOCUMENT_ROOT']."/final_ritg/includes/dbconnect.php");
$act = str_replace(" ", " ", $act);
$sql = "select `name`,`genre`, `members`, `story`, `image`, `contact_fname`, `contact_lname`, `contact_phone`, `contact_email` from `festival`.`act` where `name` = :name ;";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $act);
$stmt->execute();
echo $stmt->rowCount();
}
when 'name' only contains a single word, like 'john', the function returns 1 ($act holds 'john' as well).
How do I have to prepare my query?
Edit: I am using utf8 across the board.
Edit: This is the prepare stmt I use to insert the data:
$stmt->bindParam(':name', str_replace(' ',' ',$name));
I did so, because the query result would have been cut off at the whitespace when trying to retrieve it.
As it turns out, my mistake was not in the php, but inside the html.
I was creating a select list from a table. because the names were unique, i used those as primary keys and as value for each select-option...those dont like whitespace.
The solution here would be to either add a numbered index to the table or to do some string-conversion (but that would cause a lot of extra work preparing the string for the query) I dont yet know how I would be going over this.
Anyways, maybe another beginner runs into the same trap and finds this useful.
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.
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..