SQL syntax error: unknown column - mysql

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."')");

Related

Combine data from csv before insert into a custom datatable in wordpress

I have a MySQL query that filters all emails from a csv file and combine multiple records before inserting them to a custom datatable in wordpress. This works:
$cntSQL = "SELECT count(*) as count FROM {$tablename} WHERE email='".$email."'";
but i need a multiple condition like following but this is not working
$cntSQL = "SELECT count(*) as count FROM {$tablename} WHERE email='".$email."' AND phone='".$phone."'";
I also tried this but not working.
$cntSQL = "SELECT count(*) as count FROM {$tablename} WHERE {email='".$email."'} AND {phone='".$phone."'}";
Debugging
[09-Oct-2020 18:49:07 UTC] WordPress database error for query INSERT INTO `wp_lubuvna_subscribers` (`first_name`, `last_name`, `email`, `phone`, `birthday`, `gender`, `customer_type`, `id_company_number`, `street_address`, `address_line_2`, `city`, `state_area`, `zip`, `customer_from`, `groups`, `last_visit`, `send_sms`, `send_email`, `join_date`, `post_author`) VALUES ('Joshua', 'Hodges', 'guj#wote.bj', '(603) 280-6605', '04/25/1953', 'Male', '499242365', '79808607399', 'Jomuz Street', 'Alser Grove', 'Custipeva', 'MO', '41789', 'tada', 'pacseztoj', '08/20/1988', 'TRUE', 'TRUE', '01/10/1920', 1) made by do_action('wp_ajax_new_subscriber_batch'), WP_Hook->do_action, WP_Hook->apply_filters, maybe_insert_new_subscriber_batch_database_table
the results i am getting from follwoing:
$record = $wpdb->get_results($cntSQL, OBJECT);
results:
Array ( [0] => stdClass Object ( [count] => 0 ) )
Based on your comment you need an OR operator not AND operator.
$cntSQL = "SELECT count(*) as count FROM {$tablename} WHERE email='".$email."' OR phone='".$phone."'";

MYSQL insert from select and variables

I am trying to insert values coming from a select and variable :
INSERT INTO routeur (`codeAdherent`, `quantiteArticle`, `dateFin`) VALUES
(SELECT `codeAdherent` FROM adherents WHERE categorie = 'G', `quantiteArticle` = $a, `dateFin`= $b);
Write it with and without VALUES, with and without IN, with and without brackets but I always get an synthax error.
Where is my mistake?
Try below:
INSERT INTO routeur (codeAdherent, quantiteArticle, dateFin)
SELECT codeAdherent, #a, #b FROM adherents WHERE categorie = 'G'
You have to read carefully the INSERT syntax because you have got many errors.
This is the right syntax:
INSERT INTO routeur (codeAdherent, quantiteArticle, dateFin)
SELECT codeAdherent, '$a', '$b'
FROM adherents
WHERE categorie = 'G'
PS: To avoid the SQL Injection you should use Prepared Statements
You can try this out :
INSERT INTO routeur (codeAdherent, quantiteArticle, dateFin) VALUES
(SELECT codeAdherent FROM adherents WHERE categorie = 'G', $a, $b);

Concat function returns 1 on MySQL query on Flask

I run MySql query in flask with concat function and it always returns 1.
cur.execute("INSERT INTO jobs( job_id, job_name, company, who_created)
VALUES(%s,%s, %s,%s)",(job_id,job_name, company,
[cur.execute("select concat(first_name , ' ' , last_name)
from employees where username = %s", [username] ) ] ) )
who_created always returns 1.
When I run query on MySQLWorkbench, it works fine and returns first name + last name.
Problem is not with concat function, because even if I run it without concat, I get the "str object is not callable" error
Thanks.
cur.execute will return the number of rows found. To get the returned data, you need to use another call after the execute:
cur.execute("select concat(first_name , ' ' , last_name) from employees where username = %s", [username] )
name_rs = cur.fetchall()
cur.execute("INSERT INTO jobs( job_id, job_name, company, who_created) VALUES(%s,%s,%s,%s)",(job_id, job_name, company, name_rs[0][0] ) )

How to insert query into mysql with single quotes

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.

Return column names of mysql query

I have a MySQL query that is exported as a CSV file. The person who receives the CSV wants me to include the column headings. Obviously I can hard code them in the query but wondered if there was a way to return a row that has the names of all of the columns that have been queried?
My current query is below - I wish to programatically include the column headings too if I can just in case I forget to update it when changes are made.
Thanks
SET #sql_text =
CONCAT (
"SELECT
cf_id as FoundUsFrom,
firstname as CustomerName1,
lastname as CustomerName2,
address1 as CAddress1,
address2 as CAddress2,
'' as CAddress3,
towncity as CCity,
postcode as CPostCode,
email as 'email',
telephone as HomePhone,
mobile as MobilePhone,
'' as WorkPhone,
chidname as PName,
'' as ToBeAged,
partyaddress1 as PAddress1,
partyaddress2 as PAddress2,
'' as PAddress3,
partytowncity as PCity,
partypostcode as PPostCode,
/*NEED VALIDATION*/
celebrating as PType,
partydate as PDate,
partyboffinstart as PTime,
specialinstructions as SpecialInst,
numberguests as Guests,
IF(airexp = '','N','Y') as Air,
IF(chemcocklngexp = '','N','Y') as CocktailLong,
IF(chemcockshtexp = '','N','Y') as CocktailShort,
IF(chemreact = '','N','Y') as Reactions,
IF(dryicebolton = '','N','Y') as DryIce,
IF(electricitybolton = '','N','Y') as Electricity,
IF(flightbolton = '','N','Y') as Flight,
IF(fourelementsbolton = '','N','Y') as Elements,
IF(magicbolton = '','N','Y') as Magic,
IF(slimebolton = '','N','Y') as Slime,
IF(sweetbolton = '','N','Y') as Sweets,
IF(miniimpsbolton = '','N','Y') as MiniImps,
IF(extravaganzabolton = '','N','Y') as Extravaganza,
IF(dryicecreambolton = '','N','Y') as AIceCream,
IF(rocketbolton = '','N','Y') as ARocket,
IF(foodbreakbolton = '','N','Y') as AFood,
partybags as PBags,
deluxepartybags as PDBags
INTO OUTFILE 'PATHTO/data/bookings",
DATE_FORMAT( NOW(), '%Y%m%d%s'),
".csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
FROM sb_chronoforms_data_bookingformcombined"
);
PREPARE s1 FROM #sql_text;
EXECUTE s1;
DROP PREPARE s1;
loging this separately since it's another way to solve the issue:
select 'col_1', 'col_2','col_3','col_4' from dual UNION all select
col_1,col_2,col_3,col_4 from table_1;
that's a strange question :) try
SELECT
*
FROM
information_schema.COLUMNS
where
table_chema = 'your_schema'
and table_name = 'your_table';
than use ordinal_position to display the relevant column name