I am having with my query because Insert into value and select is not working, Is this the proper way of using it? thankyou!
This is my query line
$sql = "INSERT INTO `stud_class` (`stud_fullname`, `stud_uid`,`stud_code`, `stud_subject`, `stud_cname`,`stat`) VALUES ('$stud_full','$stud_uid',(SELECT subject_code,subsubject,class_Name FROM subject WHERE subject_code = '$subcode'),1)";
A subquery that's used as an expression is only allowed to return one value, not multiple columns.
You need to use the SELECT query as the source of all the values, not as an expression inside the VALUES list.
$sql = "INSERT INTO `stud_class` (`stud_fullname`, `stud_uid`,`stud_code`, `stud_subject`, `stud_cname`,`stat`)
SELECT '$stud_full','$stud_uid', subject_code,subsubject,class_Name, 1
FROM subject WHERE subject_code = '$subcode')";
You should also use a prepared statement rather than substituting variables into the SQL string. See How can I prevent SQL injection in PHP?
Related
I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");
I am having this piece of code:
$result = mysqli_query($con , 'SELECT * FROM messages WHERE group = "'.$_POST['group'].'" ORDER BY date '.$_POST['order'].'');
I don't understand why it is always returning me false. The variables $_POST['group'] and $_POST['order'] aren't empty .
$_POST['group']='PHP'
$_POST['order']='DESC'
The conecction to the database is corect too.
GROUP is a mysql reserved word and needs to be quoted using backticks;
SELECT * FROM messages WHERE `group` = ...
You're also wide open to SQL injection, you should never add un-validated/un-escaped POST data in string format to your SQL. The safest way to do queries with user data is using prepared statements, or - as a less secure alternative - escape the data using mysqli_real_escape_string.
$result = mysqli_query($con , "SELECT * FROM messages WHERE group = '".mysqli_real_escape_string($_POST['group'])."' ORDER BY date '".mysqli_real_escape_string($_POST['order'])."'";
Try formatting the query like this and see if it helps your result. I also added mysqli_real_escape_string() to escape your input, as your query was wide open to SQL injection.
http://php.net/manual/en/mysqli.real-escape-string.php
So, I'm working on some PHP and using prepared statements to access my database with mysqli, the following statement has a different outcome when prepared statements are used than if I
run the query using HeidiSQL, manually inserting the values
run the query without using prepared statements and manually entering the values
Prepared statement query:
$qStr = "SELECT id, head, descrip, img.dir
FROM CS_P, img,Q_Q_Items
WHERE CS_P.id = Q_Q_Items.I_ID
AND CS_P.id = img.Product_ID
AND img.priority=1
AND CS_P.id NOT IN(
SELECT ID2
FROM I_Cols, Q_Q_Items
WHERE ID2 = Q_Q_Items.I_ID
AND Q_Q_Items.Q_ID = ?
AND ID1 IN (".$madeMarks.")
)
AND Q_Q_Items.Q_ID = ?;";
Manually entered query:
SELECT id, head, descrip, img.dir
FROM CS_P, img,Q_Q_Items
WHERE CS_P.id = Q_Q_Items.I_ID
AND CS_P.id = img.Product_ID
AND img.priority=1
AND CS_P.id NOT IN(
SELECT ID2
FROM I_Cols, Q_Q_Items
WHERE ID2 = Q_Q_Items.I_ID
AND Q_Q_Items.Q_ID = 2
AND ID1 IN (35)
)
AND Q_Q_Items.Q_ID = 2;
The difference:
This statement is intended to omit rows where the value of ID_Cols.ID1 matches one of the values to be bound in place of $madeMarks. $mademarks is just a string of question marks that are inserted into the string so that I can insert numeric values that are posted to the PHP using AJAX and correspond to choices the user has previously made.
When I run this query on the SQL server directly it correctly omits rows where ID1 is in the values entered in place of $madeMarks in the prepared statement, with prepared statements these rows are always included and they shouldn't be as this means a previous choice made by the user clashes with this choice meaning it should not be displayed.
Is the way prepared statements are processed making this query impossible to be executed as intended?
Further information:
I have echoed out the values and they are correct integers, no strings or characters and all of the data is correct before it is bound to the prepared statement, I have used intval to make sure of this.
JSON encoded array of values bound to the query:
[2,35,2]
Bind type string:
'iii'
$madeMarks:
'?'
I have bound the values to the statement with 'i' binds as the database is expecting.
ID1 and ID2 are integers.
//////////////////////////////////////////////////////////////////////
It is now functional.
This isn't really an answer but is is a workaround, I just used preg_replace to replace any non-numeric chars with empty characters and then built the in statement with a for loop, inserting values from the choices array into the statement. There is no vulnerability to SQL injection as it is only numeric characters, this would be vulnerable to injection if it was a string that I had to compare.
Do not do this, it is hackish and bad, just use PDO.
I'm trying to do a MySQL query in PHP with some special characters. It seems to work if I run the query on my database with straight SQL:
SELECT SUM(quantity_ordered) FROM `shopping_cart`
WHERE `cart_number` = 10316027
AND `size` IN ('5¼" x 8¼"','5⅜" x 7¾"','4½" x 9½"')
The above query returns the expected result and SUM but when I put it in my prepared PHP query it returns no records or SUM.
I suspect that it has to do with the single quotes around each size but if I remove them I get a MySQL error. A similar query in my PHP with straight numbers and no surrounding quotes works fine.
I've tried different ways of escaping the special characters but I'm wondering if this query will work at all with these types of characters?
You problem is you are probably not escaping the double quotes in your PHP string.
try this
$qry = "SELECT SUM(quantity_ordered) FROM `shopping_cart`
WHERE `cart_number` = 10316027
AND `size` IN ('5¼\" x 8¼\"','5⅜\" x 7¾\"','4½\" x 9½\"')"
Based on your comment about the prepared statement:
SELECT SUM(quantity_ordered) FROM wholesale_shopping_cart WHERE cart_number = :cart_number AND item_number IN ($items)
You should build your $items array with individual bound variables so that it would look like:
SELECT SUM(quantity_ordered) FROM wholesale_shopping_cart
WHERE
cart_number = :cart_number
AND item_number IN (:val1, :val2, :val3)
Then you can bind your variables and execute the query.
If you put your variable directly in your sql statement, you will (probably...) have an sql injection problem and you would need to escape your quotes correctly.
Im trying to execute something like this
$SQL = "INSERT into cb_sent_alerts(user_id,message)
Select id, ' :message ' from story1";
$stmt->bindValue(':message', $_POST['message']);
But that just sends :message to the database, not the values of $_POST['message']; What can i do?
EDIT: very sorry should have specified, :message is not a column in cb_sent_alerts, rather i want the message there as a string.
Though it's never mentioned in the doc explicitly, you can work with placeholders in SELECT part of INSERT ... SELECT query the same way as with any other type of query. So this:
INSERT INTO cb_sent_alerts(user_id,message)
SELECT id, :message FROM story1
... end up with the right value (a string) if bound up by bindValue(':message', $_POST('message') call.
Note that placeholders cannot be used for the column and table names, so the thing you were afraid of is just not possible. )