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.
Related
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?
I need cut a piece of text fragment starting with "<div".
I have some like this:
$query = mysql_query("Select * from products_description");
while($row = mysql_fetch_array($query))
{
$usun = substr($row['products_description'], 0, strpos($row['products_description'], "<div"));
mysql_query('UPDATE products_description SET products_description = '.$usun.' WHERE products_id = '.$row['products_id'].'');
}
Unfortunately it does not work
If we echo out the SQL text (the UPDATE statement the code is attempting to execute), we'd see part of the problem.
String literals need to be enclosed in single quotes.
... SET products_description = 'string literal' WHERE ...
^ ^
Another issue is that we don't see any guarantee that the string literal value isn't going to include potentially unsafe values, such as a single quote. Potentially unsafe values should be properly escaped before they are included in SQL text.
Of course, if we used a prepared statement with bind placeholders, we would entirely avoid both of those problems.
Assuming that the PHP substr function is returning the value you want assigned to the column... there's really no need to process RBAR (row by agonizing row), when we could accomplish the same thing in one swoop.
UPDATE mytable SET mycol = SUBSTRING_INDEX(mycol,'<div',1) ;
We can test our expressions in a SELECT statement, before we commit to running an UPDATE statement. For example:
SELECT t.mycol
, SUBSTRING_INDEX(t.mycol,'<div',1) AS newval
FROM mytable t
Firstly, use PDO rather than mysqli_ or mysql_ functions. Then you can use parameter binding. It helps to prevent SQL injection.
You should quote your $usun before concatenating it into the SQL request:
$usun=mysql_real_escape_string($usun);
It's unclear why the exact code in your question isn't working, (although the quoting issue others have pointed out is definitely part of the problem) but this may answer the question anyway since I'm proposing something completely different.
Try just doing one update query to remove the <div at the beginning of the string instead of the select/loop/update approach.
UPDATE products_description
SET products_description = SUBSTRING(products_description FROM 5)
WHERE products_description LIKE '<div%'
Or if you want to remove everything after the <div:
UPDATE products_description
SET products_description = '<div'
WHERE products_description LIKE '<div%'
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`");
$sql="SELECT retail_peak, number from callplandata ";
$rs=mysql_query($sql,$conn);
$sql2='';
while($result=mysql_fetch_array($rs)) {
$sql2.="UPDATE callplandata set ".$_POST["callplancopy_newname"]." = '".$result[$_POST["callplancopy"]]."' where number = '".$result["number"]."'; ";
}
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
I am trying to run the above queries, i have set $sql2 with a ; on the end so i just run one query rather than many separate queries.
I am getting this Error message:
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 'UPDATE callplandata set dcabr = '0' where number = '44*116'; UPDATE callplandata' at line 1
when i echo $sql2, it looks like - http://www.wepaste.com/sql2/
mysql is deprecated but it also doesn't allow multiple statements in a single query.
You can however use multiple statements in a single query with mysqli by using mysqli_multi_query
Your immediate problem is that you are concatenating the $sql2 queries in the while loop to make one long string and then trying to execute the long string as one query.
You should move the execution of $sql2 into the while loop and drop the .= operator in favor of =:
$sql2=''; // Don't need this line
while($result=mysql_fetch_array($rs)) {
$sql2="
UPDATE callplandata
SET ".$_POST["callplancopy_newname"]."='".$result[$_POST["callplancopy"]]."'
WHERE number = '".$result["number"]."'
";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
}
You could also follow Rob's suggestion and execute the long string as a multiple query.
You would also do well to heed the warnings in the comments about SQL injection and deprecated functions.
You can actually run this as one statement by dropping the WHERE clause.. it is the same logic.
You are using an anti-pattern for what this code is trying to achieve: to update all rows in the callplancopy table (where the number column is not null) to set a column equal to a value.
(NOTE: the "WHERE number =" in the original UPDATE statement would effectively prevent rows with a NULL value in that column from being updated.)
The entire mess of code is performing RBAR (Row By Agonizing Row) what could be more simply and efficiently accomplished with just one single UPDATE statement issued to the database:
UPDATE callplandata d
SET d.`somecol` = 'someval'
WHERE d.number IS NOT NULL
(NOTE: The WHERE clause is included to reproduce the behavior of the original UPDATE statements, avoiding updating rows where the number column is NULL. If that's not desired, or is not necessary, then the WHERE clause can be omitted.)
(NOTE: This assumes that you are assigning a literal value to the column, as in the original UPDATE, where we see "callplancopy" enclosed in single quotes, making it a string literal. If you are meaning to copy the value from another column in the row, then we'd enclose the column identifier in backticks, not single quotes.)
SET d.`somecol` = d.`some_other_col`
If we insist on using the deprecated mysql interface, we really need use the mysql_real_escape_string function to make unsafe values "safe" for inclusion in the SQL text.
$sql = "UPDATE callplandata d
SET d.`" . mysql_real_escape_string($_POST["callplancopy_newname"]) . "`"
. " = d.`" . mysql_real_escape_string($_POST["callplancopy"] . "`
WHERE d.number IS NOT NULL";
# for debugging, echo out the SQL text
#echo $sql;
NOTE: The PHP mysql interface is deprecated. New development should make use of the PDO or mysqli interface.
I am currently working on a php project and used the word 'value' as a column name. The problem being that when I run the query, it overwrites all entries in the database, even though I have a delimiter (primary key = *). I have tried everything I can think of to get this to work, and it hasn't yet. here is the complete line of code:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = ".$_POST['txtValueBalance'].", Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
Note here, that $row['FK_Rev_Exp'] is the delimiter I was talking about. It is being pulled accurately from a previous query. Also, please ignore any sql injection problems, I'm just working on getting the project functional, I can optimize later.
EDIT 1: I have also tried enclosing the "value" in everything I can think of that may get rid of this problem, but no luck.
EDIT 2: I also don't think it is a problem with the statement itself, as I directly entered the statement into the mysql command line and it only affected 1 row, possibly a php problem?
EDIT 3: Full block, including the execution of the sql. Here, ExecuteSQL runs all necessary mysqli statements to execute the sql command. it takes in a sql statement and a true/false if there is a result set:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = '".$_POST['txtValueBalance']."', Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
ExecuteSQL($SqlStatement, false);
I can't figure it out, and any help would be appreciated.
I think your problem is not about mysql reserver keywords because your correctly surrounded Value with backtick and that makes database understand this is a field. I'm more concerned about treating not integers as integers so i would suggest to surround with quotes '' your value since it is a decimal
`Value` = '".$_POST['txtValueBalance']."',