Invalid query: Column count doesn't match value count at row 1 - php

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());

Related

INSERT INTO runs only 1 time?

Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");

MySQL Text Data Type Too Much?

I have about 200 characters I'm trying to insert into my database under the data type longtext and I've also tried normal text.
With longtext it lets me fit a bit more although when I try to type about 200 characters it shows that it is too long according to the MySQL error.
I'm not sure how this works as LONGTEXT can store up to 4gb of characters.
Structure:
Let me know if you need any other information!
By the way its inserting into the database using a MySQLi Query from the POST Data.
Error:
Query:
$q = $mysqli->query("INSERT INTO `lunar_casino`.`posts`(`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, '$user', '$title', '$message', '$image', '$category', NOW())");
if(!$q){
echo "<font color='red'><b>There has been an error with our database! Please contact the website administrator!</b></font><br /><br />";
echo $mysqli->error;
} else {
echo "<font color='green'><b>You have successfully added a blog post!</b></font><br /><br />";
}
This has nothing to do with size, you have an SQL error. You do not use prepared statements correctly, and seem to be pasting data verbatim in the query.
You can tell by the actual SQL error you are getting:
"... for the right syntax near 'm not making it...".
The ' character screws up the query.
To fix correctly, use a prepared statement:
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, :user, :title, :message, :image, :category, NOW())");
$stmt->bind_param(":user", $user);
$stmt->bind_param(":title", $title);
...etc...
$stmt->execute();

want to do a double MYSQL INSERT INTO to two different tables

I want to be able to insert into two different mysql tables using php with the second mysql insert being dependent on the member id of the first insert.
For example:
mysql_query("
INSERT INTO `member_users` (
`id`,
`first_name`,
`last_name`,
`username`,
`password`,
`address1`,
`address2`,
`postcode`,
`access`,
`expires`
) VALUES (
NULL,
'$fname',
'$lname',
'$email',
'$passhash',
'$add1',
'$city',
'$postcode',
'',
''
)"
);
Then I want to take the id of this member user to create a mysql_query insert on the same page eg:
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
'$userid',
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
its probably a really easy answer and a really silly question but cannot seem to find the answer anywhere
thanks in advance
If I have understood correctly, and you need to get the member_id from the first query, to use in the second query, you can use the PHP function
$the_member_id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
You can also do it without using that PHP function
$sql = "SELECT LAST_INSERT_ID()";
// add code here to run the query.
You can use the php function mysql_insert_id() to get the last id you input into the database.
EG:
$sql = "INSERT INTO `table` VALUES (NULL, 'Thomas', 'Male')";
$query = mysql_query($sql);
$id = mysql_insert_id();
So in your question after the first INSERT you need this:
$userid = mysql_insert_id();
Then your second query will work.
You can use mysql_insert_id() to get id, generated by last insert.
mysql_insert_id — Get the ID generated from the previous INSERT operation
You could use the LAST_INSERT_ID MySQL function in your second SQL statement to get the last insert ID from the first.
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
LAST_INSERT_ID(),
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
I would recommend that if you use this approach then you execute the queries within a transaction. That way there's no way that another insert can occur between your first insert and your second, thus throwing off the result of LAST_INSERT_ID.
After executing mysql_query() function you can get lastly inserted id of lastly inserted table by mysql_insert_id().
You can do something like what is done in this example
$sql = "INSERT INTO users(name,gender) VALUES ('$name','$gender')";
$result = mysql_query( $sql,$conn );
$user_id = mysql_insert_id( $conn );
$sql = "INSERT INTO website(site,user) VALUES ('$site',$user_id)";
$result = mysql_query( $sql,$conn );
Manual for mysql_insert_id

PHP foreach issue with empty fields

I have a big form
This form is processed by a PHP file called by a serialize jQuery function
foreach($_GET['claimant'] as $k=>$v) {
$insClaim = "INSERT INTO `cR_Claimants` (`memberID`, `ParentSubmission`, `Name`, `DOB`, `Company`, `Email`, `MainPhone`, `OtherPhone`, `MobilePhone`, `OwnershipPercentage`, `Address`, `ZIPcode`, `Country`) VALUES ('".$memberID."', '".$refNumb."', '".mysql_real_escape_string($v['name'])."', '".$v['DOB']."', '".mysql_real_escape_string($v['company'])."', '".$v['email']."', '".$v['mainPhone']."', '".$v['alternatePhone']."', '".$v['mobilePhone']."', '".mysql_real_escape_string($v['percentage'])."', '".mysql_real_escape_string($v['address'])."', '".$v['ZIP']."', '".$v['country']."')";
$resultinsClaim=mysql_query($insClaim) or die("Error insert Claimants: ".mysql_error());
}
The problem is that $_GET['claimant'] in certain cases can be empty. I mean that the relative field has not been entered at all.
When this happens obviously the Insert should not run when that specific $_GET['claimant'] is empty.
I tried the two following solutions, but they do not work, the Insert runs anyway, putting in my DB empty strings.
Please help.
foreach($_GET['claimant'] as $k=>$v) {
if($_GET['claimant'] != "") {
$insClaim = "INSERT INTO `cR_Claimants` (`memberID`, `ParentSubmission`, `Name`, `DOB`, `Company`, `Email`, `MainPhone`, `OtherPhone`, `MobilePhone`, `OwnershipPercentage`, `Address`, `ZIPcode`, `Country`) VALUES ('".$memberID."', '".$refNumb."', '".mysql_real_escape_string($v['name'])."', '".$v['DOB']."', '".mysql_real_escape_string($v['company'])."', '".$v['email']."', '".$v['mainPhone']."', '".$v['alternatePhone']."', '".$v['mobilePhone']."', '".mysql_real_escape_string($v['percentage'])."', '".mysql_real_escape_string($v['address'])."', '".$v['ZIP']."', '".$v['country']."')";
$resultinsClaim=mysql_query($insClaim) or die("Error insert Claimants: ".mysql_error());
}
}
AND
foreach($_GET['claimant'] as $k=>$v) {
if(!empty($_GET['claimant'])) {
$insClaim = "INSERT INTO `cR_Claimants` (`memberID`, `ParentSubmission`, `Name`, `DOB`, `Company`, `Email`, `MainPhone`, `OtherPhone`, `MobilePhone`, `OwnershipPercentage`, `Address`, `ZIPcode`, `Country`) VALUES ('".$memberID."', '".$refNumb."', '".mysql_real_escape_string($v['name'])."', '".$v['DOB']."', '".mysql_real_escape_string($v['company'])."', '".$v['email']."', '".$v['mainPhone']."', '".$v['alternatePhone']."', '".$v['mobilePhone']."', '".mysql_real_escape_string($v['percentage'])."', '".mysql_real_escape_string($v['address'])."', '".$v['ZIP']."', '".$v['country']."')";
$resultinsClaim=mysql_query($insClaim) or die("Error insert Claimants: ".mysql_error());
}
}
If $_GET['claimant'] is an array, you should ask for its length:
if (count($_GET['claimant']) > 0) { ... }
The check should be:
if(!empty($v)) {
// Stuff here
}
This is assuming that the GET variable actually contains an array of arrays.
Most likely you don't need the foreach.
This code is also vulnerable to SQL injection, all parameters needs to be escaped before entered into a SQL query
Try this instead:
$vals = $_GET['claimant'];
if(!empty($vals)) {
$query = "INSERT INTO `cR_Claimants` (`memberID`, `ParentSubmission`, `Name`, `DOB`, `Company`, `Email`, `MainPhone`, `OtherPhone`, `MobilePhone`, `OwnershipPercentage`, `Address`, `ZIPcode`, `Country`) VALUES ('".$memberID."', '".$refNumb."', '".mysql_real_escape_string($vals['name'])."', '".mysql_real_escape_string($vals['DOB'])."', '".mysql_real_escape_string($vals['company'])."', '".mysql_real_escape_string($vals['email'])."', '".mysql_real_escape_string($vals['mainPhone'])."', '".mysql_real_escape_string($vals['alternatePhone'])."', '".mysql_real_escape_string($vals['mobilePhone'])."', '".mysql_real_escape_string($vals['percentage'])."', '".mysql_real_escape_string($vals['address'])."', '".mysql_real_escape_string($vals['ZIP'])."', '".mysql_real_escape_string($vals['country'])."')";
$resultinsClaim=mysql_query($insClaim) or die("Error insert Claimants: ".mysql_error());
}
Not sure why you're using a foreach() loop here..._GET['claimant'] is probably not an array of values unless you have multiple fields on your form called claimant[].
Just do this:
$claimant = $_GET['claimant'];
if( $claimant != ""){
$insClaim = "YOUR REALLY LONG QUERY";
// etc.
}
ALSO: please, please, please use mysql_real_escape_string() on all incoming request parameters.

mysql query not inserting to database

i have a db query in php that is not inserting into database. Have used this format lots of times but for some reason its not working now. any ideas please
$query = "INSERT INTO `databasename`.`member_users` (`id`, `first_name`, `last_name`, `username`, `password`, `address1`, `address2`, `postcode`, `access`, `expires`) VALUES (NULL, '$fname', '$lname', '$email', '', '$add1', '$add2', '$postcode', '0', '')";
$result = mysql_query($query);
if($result){
echo"query inserted";
}else{
echo "nope";
}
Instead of echo "nope"; I suggest something like :
echo 'error while inserting : ['.mysql_errno().'] '.mysql_error();
echo 'query : '.$query;
This way you will be able to see the exact error and the query that was executed.
It can be a lot of things :
Constraint error with a foreign key
Data type error
Non-existent field
Wrong database or table name
Instead of...
$query = "INSERT INTO `databasename`.`member_users` ..."
do
$query = "INSERT INTO member_users ..."
Hope it works. :)
If databasename and member_users are variables then,
Instead of
$query = "INSERT INTO databasename.member_users...
do
$query = "INSERT INTO $databasename.$member_users...

Categories