I want to insert a query into a database which contain single quotes within the value. How can I handle this in PHP?
My query is:
insert into query (date_time, userid, user_traits, query_sql, status, description, is_scheduled_row)
values ('2016-01-06 02:39:01', '307', '0,3598,1937,13891,37746,22082,2596,2431,12850,3917,1234784,44712,14638,14418,12850,2631,25003,11428,27450,2592,23593,11441,2826,36330,32219,32351,20720,13997,2594,2467,15687', 'Select * from gl_base_schema.item where national_status_cd = 'A'', 'in queue', ' (Scheduled Query #413) Pull all items where National Status Code is 'A'', 1);
It shows error as
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'A'', 'in queue', ' (Scheduled Query #413) Pull all items where National Status C' at line 1
Replace your single quote(') in value to BackSlash & Single Quote (\') or two single quotes ('')
Try this:
INSERT INTO QUERY (date_time, userid, user_traits, query_sql, STATUS, description, is_scheduled_row)
VALUES ('2016-01-06 02:39:01', '307', '0,3598,1937,13891,37746,22082,2596,2431,12850,3917,1234784,44712,14638,14418,12850,2631,25003,11428,27450,2592,23593,11441,2826,36330,32219,32351,20720,13997,2594,2467,15687', 'Select * from gl_base_schema.item where national_status_cd = ''A''', 'in queue', ' (Scheduled Query #413) Pull all items where National Status Code is ''A''', 1);
OR
INSERT INTO QUERY (date_time, userid, user_traits, query_sql, STATUS, description, is_scheduled_row)
VALUES ('2016-01-06 02:39:01', '307', '0,3598,1937,13891,37746,22082,2596,2431,12850,3917,1234784,44712,14638,14418,12850,2631,25003,11428,27450,2592,23593,11441,2826,36330,32219,32351,20720,13997,2594,2467,15687', 'Select * from gl_base_schema.item where national_status_cd = \'A\'', 'in queue', ' (Scheduled Query #413) Pull all items where National Status Code is \'A\'', 1);
$query = "Select * from gl_base_schema.item where national_status_cd = 'A'";
$sql = "insert into query (date_time, userid, user_traits, query_sql, status, description, is_scheduled_row) values ('2016-01-06 02:39:01', '307', '0,3598,1937,13891,37746,22082,2596,2431,12850,3917,1234784,44712,14638,14418,12850,2631,25003,11428,27450,2592,23593,11441,2826,36330,32219,32351,20720,13997,2594,2467,15687', '."'".$query."'".', 'in queue', ' (Scheduled Query #413) Pull all items where National Status Code is \'A\'', 1)";
You can use like that with double and single quote combination:
insert into query (date_time, userid, user_traits, query_sql, status, description, is_scheduled_row)
VALUES ("2016-01-06 02:39:01","307","0,3598,1937,13891,37746,22082,2596,2431,12850,3917,1234784,44712,14638,14418,12850,2631,25003,11428,27450,2592,23593,11441,2826,36330,32219,32351,20720,13997,2594,2467,15687","Select * from gl_base_schema.item where national_status_cd = 'A'","in queue"," (Scheduled Query #413) Pull all items where National Status Code is 'A'", 1)
You can use 'A' this string into another string than you can use this as "'A' test"
Where you have 'A'', make it 'A'''. The extra ' escapes the next ', so you need '' for one '. Hope that helps.
Related
I want to insert two values in the a table.One of which is actually taken from another table with the select statement as below.
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES(SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "',#allowance_id_fk)";
There is syntax error exception as shown in the figure.
Your SQL statement is invalid. Use the following:
query = "INSERT INTO empallowance SELECT emp_id, #allowance_id_fk FROM employee WHERE emp_cnic='" + cnic + "'";
You can read all about the approach here.
you have to use bracket in sub query.
try this:
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES((SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "'),#allowance_id_fk)";
You can modify your query as below :
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) SELECT emp_id, #allowance_id_fk FROM employee WHERE emp_cnic= ' " + cnic + "'";
Add '()' between select query for a separation of insertion query.
INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES((SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "'),#allowance_id_fk)
You can't do it that way but you can create a select statement and insert its results:
"INSERT INTO empallowance (emp_id_fk,allowance_id_fk)
select emp_id, #allowance_id_fk
from employee
WHERE emp_cnic='" + cnic + "'"
Also, take note, using string concatenation to insert the parameter is vulnerable for SQL Injections - Use parameterized queries instead
You can easily do this by this, it worked for me
query = "INSERT into TABLE1 (name,city)
Select name, 'Paris' from TABLE2 where id = 1";
you can assign values directly in a select query.
Need to refer a calculated field again in the statement. Have used # to create a variable and call it back. the statement gives a error saying "#1351 - View's SELECT contains a variable or parameter" have created three variables and referred them twice. what need to be corrected in the statement
CREATE OR REPLACE view finvoice AS SELECT
`Item_tax`,
`Date`,
`Invoice_No.`,
`Order_Id`,
`Buyer_name`,
`SKU_Code`,
`Product`,
#`price` := (round((((fkdaily.`Invoice_Amount`/ fkdaily.`Quantity`)-fkdaily.`Shipping_Charge_per_item`)/1.05),2)) as `price`,
`Quantity`,
#`vat_total` := (#price)*0.05)*Quantity),2)) As `vat_total`,
#`shipping` := (`Shipping_Charge_per_item`*`Quantity`) As `shipping`,
' ' as `roundoff`,
#`price`+#'vat_total`+#`shipping` as final
`Order_Status`,
`Invoice_No.` as `Invoice_No.2` ,
`Date` as date2,
'update_sku' as `TALLY_SKU`,
'Customer Sales (f)' As `Ledger`,
'Shipping Charges fk' As `Shipping Ledger`,
'FPC' As `Portal`
From fkdaily
I'm trying to run this query:
$result = db_query("INSERT INTO `timesheets` (clientid, candid, weekending, department, orderno, basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc) VALUES (`$client`, `$cand`, `$week_ending`, `$department`, `$order_no`, `$basic_pay`, `$basic_charge`, `$ot_pay`, `$ot_charge`, `$ot2_pay`, `$ot2_charge`, `$status`, `$hue`, `$huc`)");
if($result){
print 'Success! ID of last inserted record is';
}
else {
die('Error : ' . db_error());
}
These are the values from the form
$client = db_quote($_POST['client']);
$cand = db_quote($_POST['cand']);
$order_no = db_quote($_POST['order_no']);
$department = db_quote($_POST['department']);
$week_ending = db_quote($_POST['week_ending']);
$basic_pay = db_quote($_POST['basic_pay']);
$hue = db_quote($_POST['hue']);
$basic_charge = db_quote($_POST['basic_charge']);
$huc = db_quote($_POST['huc']);
$ot_pay = db_quote($_POST['ot1_pay']);
$ot_charge = db_quote($_POST['ot1_charge']);
$ot2_pay = db_quote($_POST['ot2_pay']);
$ot2_charge = db_quote($_POST['ot2_charge']);
$status = 'cand';
The value of $client in this instance is "725". The error I am getting is Error : Unknown column ''725'' in 'field list'.
How can this be - the column name in the timesheets table is clientid. I'm trying to put the value 725 into the clientid column. Is there a syntax error somewhere? The error message doesn't seem to make sense?
When setting the values in MySQL you can't use the backtick character to denote a field, you'll need to use either ' or " to enclose your variables.
Use of a back-tick is for naming a field. It's a quirk of MySQL.
Your query line should be:
$result = db_query("INSERT INTO `timesheets` (clientid, candid, weekending, department, orderno, basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc) VALUES ('$client', '$cand', '$week_ending', '$department', '$order_no', '$basic_pay', '$basic_charge', '$ot_pay', '$ot_charge', '$ot2_pay', '$ot2_charge', '$status', '$hue', '$huc')");
The correct query would be like below one:
"INSERT INTO 'timesheets' (clientid, candid, weekending, department, orderno, basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc)
VALUES ('$client', '$cand', '$week_ending', '$department', '$order_no', '$basic_pay', '$basic_charge', '$ot_pay', '$ot_charge', '$ot2_pay', '$ot2_charge', '$status', '$hue', '$huc')
Please pay attention to the quotation marks during the creation of the query.
The INSERT statement should something like that:
INSERT INTO table_name (col_name_1, col_name_2, col_name_3) VALUES('$param_1', '$param_2', '$param_3')
Note that the table_name is written without quotation marks, while each value is delimited by a single quotes.
You can find the official documentation here and a full example here.
By the way, the query for your code should be something like that:
$sqlQuery = "INSERT INTO timesheets (clientid, candid, weekending, department, orderno,basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc) VALUES ('$client', '$cand', '$week_ending', '$department', '$order_no', '$basic_pay', '$basic_charge', '$ot_pay', '$ot_charge', '$ot2_pay', '$ot2_charge', '$status', '$hue', '$huc')";
Try this way
$result = db_query("INSERT INTO `timesheets` (clientid, candid, weekending, department, orderno, basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc) VALUES ('".$client."', '".$cand."', '".$week_ending."', '".$department."', '".$order_no."', '".$basic_pay."', '".$basic_charge."', '".$ot_pay."', '".$ot_charge."', '".$ot2_pay."', '".$ot2_charge."', '".$status."', '".$hue."', '".$huc."')");
the query is as follows
SELECT id, phonenumber CONCAT( 'A reminder for ', name, 'underfive number ', underfiveNO, 'for ', message, 'tomorrow.If shot was administered please ignore this message ' )
FROM appointment WHERE MONTH (current_date) = MONTH (appointmentdate)
AND DAY (current_date) < DAY (appointmentdate)
AND (NOT lastnotified = current_date) OR lastnotified IS NULL;
the error am getting is
ERROR 1064(42000) you have an error in your sql syntax; check the manual that corresponds to your mysql server version for the right syntax to use near '('A reminder for',name,'under five number',undefiveNo, 'for', message'at line1
You forgot a comma
SELECT id, phonenumber, CONCAT( '...
^-----------------herre
There should be separator in between phonenumber and CONCAT() in your query: try with this
SELECT id, phonenumber, CONCAT('A reminder for ', name, ' underfive number ', underfiveNO, ' for ', message, ' tomorrow. If shot was administered please ignore this message' )
FROM appointment WHERE MONTH (current_date) = MONTH (appointmentdate)
AND DAY (current_date) < DAY (appointmentdate)
AND ((NOT lastnotified = current_date) OR lastnotified IS NULL);
and also as you are adding a OR condition on lastnotified column, it should be enclosed with in paranthesis to meet either of the condition
There are two columns in a MySQL table: SUBJECT and YEAR.
I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.
How can I do this? Is it possible to use a simple operator like +?
You can use the CONCAT function like this:
SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`
Update:
To get that result you can try this:
SET #rn := 0;
SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(#rn := #rn+1,3,'0'))
FROM `table`
You can use mysql built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change field name as your requirement
then the result is
and if you want to concat same field using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
then this is output
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
In query, CONCAT_WS() function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
I have two columns:
prenom and nom so to concatenate into a column with name chauffeur_sortant I used this script:
SELECT date as depart, retour, duree_mission, duree_utilisation, difference, observation, concat( tb_chaufeur_sortant.prenom, ' ', tb_chaufeur_sortant.nom) as chauffeur_sortant, concat(tb_chaufeur_entrant.prenom, ' ', tb_chaufeur_entrant.nom) as chauffeur_entrant
FROM tb_passation
INNER JOIN tb_vehicule
ON tb_vehicule.id = tb_passation.id_vehicule
INNER JOIN tb_chaufeur_sortant
ON tb_chaufeur_sortant.id = tb_passation.id_sortant
INNER JOIN tb_chaufeur_entrant
ON tb_chaufeur_entrant.id = tb_passation.id_entrant WHERE tb_vehicule.id = '';
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');