I am trying to insert a row into my data base, but what ever i seem to do I am always getting an error.
Sometimes I get parse errors and sometimes I get column errors.
Here is my code.
Thanks in advance.
<?php
include_once('config.php');
$asin = $_POST['asin'];
// $title = "<script>document.write(title)</script>";
// $mpn = "<script>document.write(mpn)</script>";
// $price = "<script>document.write(price)</script>";
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ($asin, "test", 1, 2)";
// $sql = 'INSERT INTO amazon'.
// '(asin, title, mpn,price) '.
// 'VALUES ('{$asin},' "test", 1, 2)';
mysql_select_db('amazon');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
?>
You need to use '' against your variable $asin as:
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ('".$asin."', 'test', 1, 2)";
Note:-
You can't use double quotes in double quotes. Replace double
quote(") with single quote(') around test value.
use variables in single quotes.(Example - $asin to '$asin')
Replace your query with this:-
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ('$asin', 'test', 1, 2)";
You have made two mistakes. in
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ($asin, "test", 1, 2)";
$asin and "test".
if $asin is an integer value always THEN it's okay otherwise you have to write it '".$asin."'
and for "test" the error is the comma you use here (") because you query is starting with same (") comma, so when you put same comma before test then query ends here and give you error. So replace this comma by (').
replace "test" by 'test'.
Now correct query is -
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ('".$asin."', 'test', 1, 2)";
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I'm not sure why it's not inserting any data.
No errors are returned.
I'm new in the mysql scene so i might be doing something wrong..
Do you guys mind pointing me towards the right direction?
$link = mysqli_connect("localhost", "root", "", "testdatabase");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
else if ($command == 'create-key'){
$keys = $_GET['nkey'];
if (empty($_GET['nkey'])){
print('Error: No key specified to create!');
die();
}
print ('Key '. $_GET['nkey'] .' has been created.');
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('. $keys .', 0)");
}
SQL Code:
CREATE TABLE `keys` (
`key` varchar(15) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
There is no need of ()
Change Query From
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('. $keys .', 0)");
To
$sql = "INSERT INTO `keys` (`key`, `status`) VALUES ('$keys', 0)";
And then Execute this Query
You'll probably need this on top of your script to see PHP errors:
<?php
ini_set('display_errors', 'on');
error_reporting ( E_ALL );
To help you with your error, have a look at your query.
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('. $keys .', 0)");
While this is should insert . $keys . in your table, please try:
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('". $keys ."', 0)");
I am having a hard time figuring out the exact code. It is possible I have the wrong syntax or a very limited knowledge of doing the same. Any assistance is appreciated.
$Game = array('ASIN' => $field->ASIN,
'title' => $field->title,
'price' => $field->price,
'quantity' => $field->quantity);
$sql = "INSERT INTO GameTable (`ASIN`, `Title`, `Price`, `Quantity`) "
. "VALUES ($Game['ASIN'], $GAME['title'], "
. "$GAME['price'], $GAME['quantity'])"
this code:
$sql = "INSERT INTO GameTable (`ASIN`, `Title`, `Price`, `Quantity`) "
. "VALUES ($Game['ASIN'], $GAME['title'], "
. "$GAME['price'], $GAME['quantity'])"
should become
$asin = $game['asin'];
$title = $game['title'];
$price = $game['price'];
$quantity = $game['quantity'];
$sql = "INSERT INTO GameTable (`ASIN`, `Title`, `Price`, `Quantity`)
VALUES ('$asin', '$title', '$price', '$quantity')";
Take care of using capital letters noting that php variables are case sensitive.
I am trying to send a variable as string in SQL statement to my DB function, which should then use that string as variable and do the processing.
Its multiple insert script (as array) needing the last insert ID, here's a shorten code:
$insertID = "$"."insertID";
$sql = array("first INSERT Script", "INSERT into blah(`ID`, `Name`)
VALUE ('$insertID', '$name')", "Third script");
$result = dbInsert($sql);
if ($result){
// do something
}
Here's the insert function, I am experimenting if this way would work:
function dbInsert($sql){
$con = dbConnect();
try {
// begin a transaction
mysqli_begin_transaction($con);
foreach ($sql as $value) {
if ($con-> query($value)) {
$insertID = $con-> insert_id;
} else {
trigger_error(mysqli_error($con));
}
}
// if no error, commit.
mysqli_commit($con);
} catch (Exception $e) {
// if any error, catch the exception and rollback
mysqli_rollback($con);
}
/* close connection and return the result */
$con->close();
return $insertID;
}
Please note the first script doesn't require any last insert Id, but subsequent ones do. I know I can do individual inserts and skip this whole way, but it would be good if I just send one array of SQLs and function does the insert and sends back the last insert ID (to verify).
When I echo (& die) the SQL statement in Function dbInsert has "$result" (value of $insertID), but its reading it as string and not as the variable, which holds the last insert ID. I have tried few combination but to no avail.
Current:
INSERT INTO `tblstudent` (`userid`, `scholarnumber`, `firstname`, `middlename`, `lastname`, `datecreated`)
VALUES ($result, '35566', 'Joe', '', 'Blog', CURRENT_TIMESTAMP);
Should be:
INSERT INTO `tblstudent` (`userid`, `scholarnumber`, `firstname`, `middlename`, `lastname`, `datecreated`)
VALUES ('418', '35566', 'Joe', '', 'Blog', CURRENT_TIMESTAMP);
I hope I am making sense and someone would be able to point me in the right direction. Much appreciate your time and help, thank you!
It turns out, I was going about it the wrong way. All I needed to do was pass on "LAST_INSERT_ID()" instead of passing variable etc. Thank you for all the help! Someone might benefit from this, hence updating the post.
To turn a string variable name into the actual variable, you will need to use eval, and to reformat the string that you are sending to dbInsert. At present, you're using double quotes, and the variables are being interpolated by PHP before you send them. You need to send $insertID as text, so it should be in single quotes. Compare these two:
$name = 'Percy';
$sql = array(
'INSERT into blah(`ID`, `Name`) VALUE (\'$insertID\', \'' . $name . '\')',
"INSERT into blah(`ID`, `Name`) VALUE ('$insertID', '$name')");
dbInsert($sql);
function dbInsert( $arr ){
foreach ($arr as $a) {
echo "$a\n";
}
...
Output:
INSERT into blah(`ID`, `Name`) VALUE ('$insertID', 'Percy')
INSERT into blah(`ID`, `Name`) VALUE ('', 'Percy')
So, use single quotes. Then, to interpolate the value, do the following:
eval("\$a = \"$a\";");
Here's a full example:
$name = 'Percy';
$sql = array(
'INSERT into blah(`ID`, `Name`) VALUE (\'$insertID\', \'' . $name . '\')',
"INSERT into blah(`ID`, `Name`) VALUE ('$insertID', '$name')"
);
dbInsert($sql);
function dbInsert( $arr ){
$insertID = '12345';
foreach ($arr as $a) {
echo "String before: $a\n";
eval("\$a = \"$a\";");
echo "String eval'd: $a\n";
}
}
Output:
String before: INSERT into blah(`ID`, `Name`) VALUE ('$insertID', 'Percy')
String eval'd: INSERT into blah(`ID`, `Name`) VALUE ('12345', 'Percy')
String before: INSERT into blah(`ID`, `Name`) VALUE ('', 'Percy')
String eval'd: INSERT into blah(`ID`, `Name`) VALUE ('', 'Percy')
Once you have the value of $insertID in your script, you can then run the eval to turn $insertID into a variable, which will then be interpolated.
I am taking table name as php variable to insert data into table.
But it gives error. What's bad here?
if($flag == 1)
$table = 'frrole_pupolar_article';
else
$table = 'frrole_category_article';
$insertQuery1 = "INSERT INTO '.$table.' (`url`, `sentiment`, `category`, `title` ,`time`,`img_url`,`rt_count`,`tweet_count`) VALUES ('".$url."','".$setiment."','".$category."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."')";
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 ''.frrole_category_article.' (`url`, `sentiment`, `category`, `title` ,`time`,`im' at line 1
$insertQuery1 = "INSERT INTO '" .$table. "' (`url`, `sentiment`, `category`, `title` ,`time`,`img_url`,`rt_count`,`tweet_count`) VALUES ('".$url."','".$setiment."','".$category."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."')";
You wrongly written '.$table.' instead of '" .$table. "'
Just do
$insertQuery1 = "INSERT INTO $table (`url`, `sentiment`, `category`,
`title` ,`time`,`img_url`,`rt_count`,`tweet_count`)
VALUES ('".$url."','".$setiment."','".$category."',
'".$title."','".$time."','".$img_url."','".$rt_count."',
'".$tweet_count."')";
remove the concatenations and single quotes
If your string is $insertQuery1 = "INSERT INTO '.$table.' (url,sentiment,
You cannot escape it by using single quotes '..'
Just do double quotes:
$insertQuery1 = "INSERT INTO ".$table." (`url`, `sentiment`, ....
also for all that is holy, use damn {} for if(){} statements, not using them is poor form
I have a strange problem, I'm sending an SQL query through PHP:
INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('','1','2010-10-27 13:22:59','2010-10-27 13:22:59','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding')
And it throws me this error:
Invalid query: Column count doesn't match value count at row 1.
Although, when I paste and run the same exact query in PhpMyAdmin, it works perfectly, so it got me quite confused...
I counted the number of columns and the the number of values, and they match (19). I tried to remove the 'id' field, since it's auto-incremented, but it didn't change anything. What am I doing wrong? And why does it work in PhpMyAdmin?
Thanks for any help!
EDIT:
here's the php code:
$values = array('', 1, $lastUpdated, $entry_date, $entry_ip, $streetName, $cityId, $listing['stateorprovince'], $listing['postalcode'], $listing['type'], $listing['listprice'], $has_garage, $has_indoor_parking, $has_outdoor_parking, $has_pool, $has_fireplace, $average_nb_room, $listing['yearbuilt'], $listing['exteriortype']);
$q = "INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('".htmlentities(implode("','",$values),ENT_QUOTES)."')";
$this->execMysqlQuery($q);
and the method that is being called:
private function execMysqlQuery($q, $returnResults = false, $returnInsertId = false){
$c = mysql_connect(DB_SERVER,DB_LOGIN,DB_PASSWORD);
mysql_select_db(DB_NAME, $c);
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error(). "<br/>=>".$q);
}
if ($returnInsertId)
return mysql_insert_id();
mysql_close($c);
if ($returnResults)
return $result;
return true;
}
And the error:
Invalid query: Column count doesn't match value count at row 1
=>INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`) VALUES ('','1','2010-10-27 13:47:35','2010-10-27 13:47:35','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding')
If you print $q, I'm willing to bet it'll look like this:
INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('','1','2010-10-27 13:22:59','2010-10-27 13:22:59','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding');
(I don't have PHP at work; this is a guess)
In other words, htmlentities is turning your quotes into HTML Entities. Specifically, turning ' to '
Don't use htmlentities on things that aren't being sent to the web browser. Use your database driver's escaping method (mysql_real_escape_string) on each individual value being sent in.
Edit: Better yet, use prepared statements and data binding with MySQLi or PDO, which will automatically escape the data as you bind it.
if ($insert) {
$query = "INSERT INTO employee VALUES ($empno,'$lname','$fname','$init','$gender','$bdate','$dept','$position',$pay,$dayswork,$otrate,$othrs,$allow,$advances,$insurance,'')";
$msg = "New record saved!";
}
else {
$query = "UPDATE employee SET empno=$empno,lname='$lname',fname='$fname',init= '$init',gender='$gender',bdate='$bdate',dept='$dept',position='$position',pay=$pay,dayswork=$dayswork,otrate=$otrate,othrs=$othrs,allow=$allow,advances=$advances,insurance=$insurance WHERE empno = $empno";
$msg = "Record updated!";
}
include 'include/dbconnection.php';
$result=mysql_query ($query,$link) or die ("invalid query".mysql_error());