To Start.. I am using mysqli_real_escape_string() on every text field, and leaving INT as they are:
The following query successfully inserts the record into the table without fail, every field is correctly stored... There has to be something I'm being glib about, I have blurry coding eyes at this point... But after the INSERT statement is run, mysqli_error($con) tosses the following error:
1064: 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 '1' at line 1
(I'm nearly 100% certain I do not even use the number 1 at all, whether it be in the php code or a value)
$query = mysqli_query($con,"INSERT INTO hj_media
(mediaID,MedDropID,MediaName,GLCode,Store,MediaType,MiscDetail,ArtDueDate,RunDate,EndDate,AdvMonth,Size,Dimensions,TotalCost,HJShare,CoOpShare,Vendor,HamiltonFiscal,VendorFiscal,AdDescription,Category,AddedtoVCM,ArtworkRequested,InvoiceProcessed,BilledVendor,NetCost,ProductionCost,CostPiece,QuantityOrdered,HJCostPrinting,Postage,DDFee,EventDescription,EventDate,DateToPrint,DateInMail,DateInHome,TotalPrintQuantity,TotalMailFile,TotalActualMail,ReturnedPieces,SalesResultsUnits,SaleResultsDollars,SpendNonPrint,SpendPrint,SpendAdvertising,SpendPR,MediaNameOther,ClientPersona,Campaign)
VALUES(NULL,$add_medid,'$add_vehicle',$add_glcode,'$add_loclist','$add_type','$add_miscdetails','$add_artdate','$add_rundate','$add_enddate','$add_month','$add_size','$add_dimensions','$add_totalcost','$add_hjshare','$add_coopshare','$add_vendor',$add_hamiltonfiscal,$add_vendorfiscal,'$add_addescription','$add_category','$add_addedtovcm','$add_artworkrequested','$add_invoiceprocessed','$add_billedvendor','$add_netcost','$add_productioncost','$add_costperpiece',$add_quantityordered,'$add_hjprintcost','$add_postage','$add_ddfee','$add_eventdescription','$add_eventdate','$add_datetoprint','$add_dateinmail','$add_dateinhome',$add_printquantity,$add_totalmailfile,$add_totalactualmail,$add_returnedpieces,$add_salesunits,'$add_salesdollars','$add_spendnonprint','$add_spendprint','$add_spendadvertising','$add_spendpr','$add_medianameother','$add_persona','$add_campaign')");
if (mysqli_query($con, $query)) {
echo "New record created successfully";
}
else {
echo mysqli_errno($con) . ": " . mysqli_error($con) . "\n";
}
UPDATED QUERY, TRY THIS
$query="INSERT INTO hj_media
(mediaID,MedDropID,MediaName,GLCode,Store,MediaType,MiscDetail,ArtDueDate,RunDate,EndDate,AdvMonth,Size,Dimensions,TotalCost,HJShare,CoOpShare,Vendor,HamiltonFiscal,VendorFiscal,AdDescription,Category,AddedtoVCM,ArtworkRequested,InvoiceProcessed,BilledVendor,NetCost,ProductionCost,CostPiece,QuantityOrdered,HJCostPrinting,Postage,DDFee,EventDescription,EventDate,DateToPrint,DateInMail,DateInHome,TotalPrintQuantity,TotalMailFile,TotalActualMail,ReturnedPieces,SalesResultsUnits,SaleResultsDollars,SpendNonPrint,SpendPrint,SpendAdvertising,SpendPR,MediaNameOther,ClientPersona,Campaign) ";
$query.=" VALUES(NULL,$add_medid,'$add_vehicle',$add_glcode,'$add_loclist','$add_type','$add_miscdetails','$add_artdate','$add_rundate','$add_enddate','$add_month','$add_size','$add_dimensions','$add_totalcost','$add_hjshare','$add_coopshare','$add_vendor',$add_hamiltonfiscal,$add_vendorfiscal,'$add_addescription','$add_category','$add_addedtovcm','$add_artworkrequested','$add_invoiceprocessed','$add_billedvendor','$add_netcost','$add_productioncost','$add_costperpiece',$add_quantityordered,'$add_hjprintcost','$add_postage','$add_ddfee','$add_eventdescription','$add_eventdate','$add_datetoprint','$add_dateinmail','$add_dateinhome',$add_printquantity,$add_totalmailfile,$add_totalactualmail,$add_returnedpieces,$add_salesunits,'$add_salesdollars','$add_spendnonprint','$add_spendprint','$add_spendadvertising','$add_spendpr','$add_medianameother','$add_persona','$add_campaign');";
$result =mysqli_query($con,$query);
If($result){
echo "Success"';
}
else{
echo " query failed ". mysqli_errno();
}
The problem is yoir sending a boolean gotten from the first query test into another mysqli query function. It's a good thing to have set a variable that refernces your query string, so that you use but this value in the mysqli query function . Try this
$query="put your myqli query here;";
$result =mysqli_query($con,$query);
If($result){
echo "Success"';
}
else{
echo " query failed ". mysqli_errno();
}
can you knidly thick the question answered if this solves your problem ?
I am trying to do simple insert in php and MySQL.
The HTML form has 3 fields with 1st one being mandatory and other 2 optional.
their names being :
name, address and phoneno
table name is users : id(int)|name(varchar)|address(varchar)|phoneno(int) , id is primary-key and auto-increment
and all except name and id are allow-nulls
assuming i have connection created and held in $con ,providing a value just for name and submitting the form
$name = $_POST['name']?$_POST['name']:NULL;
$address= $_POST['address']?$_POST['address']:NULL;
$phoneno= $_POST['phoneno']?$_POST['phoneno']:NULL;
$q="INSERT INTO users (name,address,phoneno)
VALUES('{$name}','{$address}',{$phoneno})";
if(mysql_query($q,$con)){
echo "data inserted successfully";
}
else{
echo "ERROR: ".mysql_error();
}
Is giving me
ERROR: 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 ')' at line 1
Never do this in production environments! But for learning, try this:
$name = $_POST['name']?$_POST['name']:'NULL';
$address= $_POST['address']?$_POST['address']:'NULL';
$phoneno= $_POST['phoneno']?$_POST['phoneno']:'NULL';
$q="INSERT INTO users (name,address,phoneno) VALUES('$name','$address',$phoneno)";
if(mysql_query($q,$con)){
echo "data inserted successfully";
}
else{
echo "ERROR: ".mysql_error();
}
You have to use 'NULL' as string
Do not wrap variables with {}. this is only needed when you use object properties like {$obj->foo}
There are some other serious security issues in this code like sql injection. So never do this in production environments!
I am receiving the error:
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 'long='-96.7812', label='abc' WHERE id='2'' at line 1
Here is my code:
$db=mysqli_connect($server,$username,$password,$dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
$sql="UPDATE locations SET name='$_POST[modname]', lat='$_POST[modlat]', long='$_POST[modlong]', label='$_POST[modlab]' WHERE id='$_SESSION[locnid]'";
echo $sql;
if (!mysqli_query($db,$sql)) {
die('Error: ' . mysqli_error($db));
}
echo "1 record modified";
mysqli_close($db);
The $sql string echoed is this:
UPDATE locations SET name='Baylor', lat='32.7923', long='-96.7812', label='abc' WHERE id='2'
I don't see anything wrong with that.
I tried escaping the values (didn't think it would help and it didn't):
$sql="UPDATE locations SET name='".mysqli_real_escape_string($db, $_POST[modname])."', lat='".mysqli_real_escape_string($db, $_POST[modlat])."', long='".mysqli_real_escape_string($db, $_POST[modlong])."', label='$_POST[modlab]' WHERE id='$_SESSION[locnid]'";
I get the same error and the same $sql string echoed out.
Thought maybe it had to do with the decimal points messing up the $sql string assignment, but even with whole numbers I get the same error.
Please help - if you can spot what the syntax error could possible be!
The column name long you have used is a reserved word in MySQL , Enclose it in backticks !
See here [An exerpt from your query]
g($db, $_POST[modlat])."', `long`='".mysqli_real_es
^ ^ ----- Enclose it like this
Try this:
$sql="UPDATE locations SET name='$_POST[modname]', lat='$_POST[modlat]', `long`='$_POST[modlong]', label='$_POST[modlab]' WHERE id='$_SESSION[locnid]'";
The column name long is a reserved word in MySQL. It should be enclosed between backticks.
Im fairly new to both PHP and SQL but what i want is for the details entered into my form to be inserted into a database.
The code i have written works and the data is submitted into the database but there are a couple things not right.
Firstly here is the code;
<?php
include "credentials.php";
function insert_post($cnhost,$cnusername,$cnpassword,$cndatabase,$titlein,$contentin,$comment_optionin) {
$connect = mysqli_connect($cnhost,$cnusername,$cnpassword,$cndatabase);
if (mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "Connection Success! <br>";
$submitpost_query = mysqli_query($connect,"INSERT INTO blog_posts (title,content,comment_option) VALUES ('".$titlein."','".$contentin."','".$comment_optionin."')");
if (!mysqli_query($connect,$submitpost_query))
{
die('Error: ' . mysqli_error($connect));
}else{
echo "Post submitted.";
}
mysqli_close($connect);
}
}
$title = $_POST["title"];
$content = $_POST["content"];
$comment_option = $_POST["comment_option"];
insert_post($host,$username,$password,$database,$title,$content,$comment_option);
?>
Although the data is submitted into the database as i want i get the following error;
"Error: 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 '1' at line 1"
The $comment_option variable contains the value 1 or 0, depending on which radio button is selected so this error might be referring to this variable but this SQL error is the same whether the value of $comment_option is 1 or 0.
I do see "Connection success!" before this error but do not see "Post submitted" even though the post is actually submitted. Any ideas why?
As well as helping me with this problem i would be very grateful if somebody could give me some general tips to improve what iv wrote. I am a noob so im sure there's a few things that could be improved here!
Thanks very much!
The problem is here:
if (!mysqli_query($connect,$submitpost_query))
You're passing a mysqli_query result which is $submitpost_query to another mysqli_query which is in the if statement.
The problem is with following chunk of code
if (!mysqli_query($connect,$submitpost_query))
it should be instead following
if (!$submitpost_query)
Reason : You are executing return object again through mysql_queri function that is causing warning, invalid resource, as this function only excepts valid sql query or connection object
I know your question is answered but I seriously recommend you to sanitize the POST data before concatenating it in a query.
while($row=mysql_fetch_array($result2)){
//return $row['ProjectID'];
$sql="INSERT INTO `tycodashboard` (ProjectID,DesignationID,ReqcompID,IntOrgID,FinishedTimeID,ProjectStatusID,PhaseID
) VALUES('{$row['ProjectID']}','$pm,'$req','$initiating,'$initiating','$ftime,'$ProjectStatus,'$Phase)";
$result=mysql_query($sql);
if(!$result){
if(mysql_errno() == ER_DUP_ENTRY){
throw new Exception("INSERT FAILED.\n\nThe database already contains a Project with the Project Name \"$ldesc\", please pick another.");
}else{
throw new Exception("INSERT FAILED.\n\n".mysql_error());
}
}
}//exits
INSERT FAILED.
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 '3','2,'2','2,'2,'3)' at line 2
You are missing a whole bunch of quotes as you can see from the error message:
'3','2,'2','2,'2,'3
Try adding the quotes where they are missing and see if that helps:
$sql="INSERT INTO `tycodashboard` (ProjectID,DesignationID,ReqcompID,IntOrgID,FinishedTimeID,ProjectStatusID,PhaseID
) VALUES ('{$row['ProjectID']}','$pm','$req','$initiating','$initiating','$ftime','$ProjectStatus','$Phase')";