This question already has an answer here:
mysqli insert error incorrect syntax [duplicate]
(1 answer)
Closed 3 years ago.
I am trying to do a small project. My task to create an update form with HTML and PHP. But I am getting this error given below:
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 's standard dummy text ever since the 1500s, when an unknown printer.' , exp_time' at line 1
I am using Laragon for php and HeidiSQL 9.5 for mysql server.
My database connection is okay. I can fetch data from the database using the SELECT query in the same file. I think something is wrong in my code. So please help me the code is given below:
<?php
require('auth.php');
require('db.php');
$id=$_REQUEST['id'];
$query = "SELECT * FROM experience where expid='".$id."'";
$result = mysqli_query($con,$query) or die ( mysqli_error($con));
$row = mysqli_fetch_assoc($result);
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$exp_title = $_REQUEST['exp_title'];
$exp_description = $_REQUEST['exp_description'];
$exp_time = $_REQUEST['exp_time'];
$update="UPDATE experience SET exp_title='".$exp_title."' , exp_description='".$exp_description."' , exp_time='".$exp_time."'
WHERE expid='".$id."'";
mysqli_query($con, $update) or die ( mysqli_error($con));
$status = "Record Updated Successfully. </br></br>
<a href='dashboard.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
You need to escape the single quotes using php's str_replace, e.g.:
$exp_title = str_replace("'", "\'", $_REQUEST['exp_title']);
$exp_description = str_replace("'", "\'", $_REQUEST['exp_description']);
$exp_time = $_REQUEST['exp_time'];
$update="UPDATE experience SET exp_title='".$exp_title."' , exp_description='".$exp_description."' , exp_time='".$exp_time."'
WHERE expid='".$id."'";
However, you should really really use preparedstatements instead of concatenating strings and escaping characters, e.g.:
$exp_title = $_REQUEST['exp_title'];
$exp_description = $_REQUEST['exp_description'];
$exp_time = $_REQUEST['exp_time'];
$stmt = $conn->prepare("UPDATE experience SET exp_title= ?, exp_description = ?, exp_time = ? WHERE expid = ?");
$stmt->bind_param("types", $exp_title, $exp_description, $exp_time, $id);
How can I search for a name in my table if there is an apostrophe in the name?
If I insert name with an apostrophe like Ender's Game in my search box, it gives an error.
I already tried solutions provided on stackoverflow, but I am not able to solve this.
Here is my code:
$string1 = $_GET['name'];
$quer = "SELECT * FROM info WHERE name = '$string1'";
$q = mysqli_query($conn, $quer);
If there is an apostrophe in $_GET['name'], an error is shown.
How can I solve this?
Code in that form is vulnerable to SQL injection. Use mysqli::prepare instead:
$string1 = $_GET['name'];
$quer = "SELECT * FROM info WHERE name = ?";
$stmt = $conn->prepare($quer);
$stmt->bind_param('s', $string1);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
var_export($result);
If you're adapting legacy, insecure code, it may be faster to use mysqli_real_escape_string. This should be reserved as a last resort, but it's there if you need it, and it's better than a regex.
The best practice that you can expect to hear over and over again from knowledgeable StackOverflow volunteers is to use prepared statements to ensure query security and reliability.
For your case, I recommend the following snippet which not only safely executes your SELECT query, but also provides informative diagnostic/debugging checkpoints throughout the process and allows you to process the resultset - represented by an multi-dimensional associative array.
$_GET['name'] = "vinay's name";
$string1 = $_GET['name'];
if (!$conn = new mysqli("host", "user", "pass", "db")) {
echo "Database Connection Error: " , $conn->connect_error; // do not show this to public
} elseif (!$stmt = $conn->prepare("SELECT * FROM info WHERE name = ?")) {
echo "Prepare Syntax Error: " , $conn->error; // do not show this to public
} elseif (!$stmt->bind_param("s", $string1) || !$stmt->execute()) {
echo "Statement Error: " , $stmt->error; // do not show this to public
}else{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
var_export($row); // do what you like here
}
}
It is important to note that using $stmt->bind_result($result) (like in Zenexer's answer) will not work (generates $result = NULL) if the info table contains more than one column (I assume it will work with one column, but I didn't test); and it will generate a Warning because of an imbalance between the number of selected columns from SELECT * and the number of nominated variables.
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
If you want to enjoy the benefits of explicitly binding a result variable, you should specify your desired columns in the SELECT clause like this:
if (!$conn = new mysqli("host", "user", "pass", "db")) {
echo "Database Connection Error: " , $conn->connect_error; // do not show this to public
} elseif (!$stmt = $conn->prepare("SELECT id FROM info WHERE name = ?")) {
echo "Prepare Syntax Error: " , $conn->error; // do not show this to public
} else {
if (!$stmt->bind_param("s", $string1) || !$stmt->execute() || !$stmt->bind_result($id)) {
echo "Statement Error: " , $stmt->error; // do not show this to public
} else {
while ($stmt->fetch()) {
echo "<div>$id</div>";
}
}
$stmt->close();
}
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 ?
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>