MYSQL Column Count error in sql query of project in PHP - php

$logquery="INSERT INTO new_data_entry_log (directory,ip,description,state,status,instituteid,email,category,bandwidth,project,institutehead,contactnumber,landlinenumber,latitude,longitude,clientip,added by,added on,added at) VALUES ('$directory','$ipaddress','$description','$state','$status','$instituteid','$contactemail','$bandwidth','$institutehead','$contactNumber','$contactlandlinenumber','$latitude','$longitude','$clientip','$name','$currentdate','$currenttime')";

I can see there is a mismatch of columns count and related values count. Probably it might be the issue.
Did you try with removing the single quates of the variables?

I have formated your query.
Formated Query
$logquery="INSERT INTO `new_data_entry_log`(
`directory`,
`ip`,
`description`,
`state`,
`status`,
`instituteid`,
`email`,
`category`,
`bandwidth`,
`project`,
`institutehead`,
`contactnumber`,
`landlinenumber`,
`latitude`,
`longitude`,
`clientip`,
`added by`,
`added on`,
`added at`
) VALUES(
'$directory',
'$ipaddress',
'$description',
'$state',
'$status',
'$instituteid',
'$contactemail',
'$bandwidth',
'$institutehead',
'$contactNumber',
'$contactlandlinenumber',
'$latitude',
'$longitude',
'$clientip',
'$name',
'$currentdate',
'$currenttime'
)";
In your code
new_data_entry_log(19 property)
But
VALUES(17 values)
This is the main reason. Another reason can be data type issue.
Because you set all values as String/Varchar
Note: best practice(underscore) for database fields
`added by` --> 'added_by'
`added on` --> 'added_on'
`added at` --> 'added_at'

Related

INSERT results in DUPLICATE ENTRY '0' FOR KEY PRIMARY

I am using a simple php script to insert data into database but it's failing. The query just doesn't become successful without showing a single error which is why I am unable to figure out the problem. Some expert here help me please.
echo $name." ".$email." ".$pass." ".$phone." ".$area." ".$specialization." ".$city." ".$latitude." ".$longitude;
The result of echo is normal - without any null elements.
$query = mysqli_query($conn, "INSERT INTO users (name, email, pass, phone, area, specialization, hospital, city, latitude, longitude)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ");
if ($query) {
echo "Status: Registeration Successful!";
// creating directory for user and storing dummy profile picture
//mkdir('../profiles/'.$email_trim, 0777);
//$result_copy = copy("img/dp.jpg.jpg", "../profiles/".$email_trim."/dp.jpg.jpg");
} else {
echo "Status: Err";
}
This "Status: Err" is always printed. I don't know why.
P.S I have double checked the database the field labels are fine.
UPDATE 1:
I added the
die(mysqli_error($conn));
statement and it says "DUPLICATE ENTRY '0' FOR KEY PRIMARY'.
PROBLEM AND SOLUTION:
The issue was that I had an 'id' field which was primary key of the table but it was not set to AUTO_INCREMENT. So, whenever I tried to insert a new record, I was actually inserting entries with duplicate PKs which was the issue. I change it to AUTO_INCREMENT and it solved the problem.
It seems you try to insert a new element with a PK = 0, but there is already a record with this key !
What is the primary key of your table ? Do you use an "id" field which is not shown in your insert statement ? Is this field AUTO_INCREMENT ?
It would be helpful to see the structure of your 'users' table.
Wild guess: looks like you may have defined an "id" column (or with whatever other name) which is primary key with default value "0", but it's not auto increment. That way you can insert 1 row and it will get "0" as "id" column's value, but you cannot insert another row because it will also try to use default value "0", which cannot happen as primary key has to be unique.
If that is the case, then please alter users table and make sure that the primary key column is also 'auto increment'.
Please check the proper error by adding below mentioned code inside else:
echo mysqli_errno($conn) . '----' . mysqli_error($conn);
<?php
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
$query = mysqli_query($conn, "INSERT INTO `users` (`name`, `email`, `pass`, `phone`, `area`, `specialization`, `hospital`, `city`, `latitude`, `longitude`)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ") or die(mysqli_error());
$query = mysqli_query($conn, "INSERT INTO `users` (`name`, `email`, `pass`, `phone`, `area`, `specialization`, `hospital`, `city`, `latitude`, `longitude`)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ");
use ` Tick maybe because there's some reserved word in your fields.
I think you doubled your close parenthesis and do not put $conn inside the query..
$query = "INSERT INTO users (name, email, pass, phone, area, specialization, hospital, city, latitude, longitude)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude')";
mysqli_query($query, $conn);
Something like this. I hope this helps

sing Variable in MySQL

Using Variable in MySQL
I have tried many possibilities and consulted a number of sources but still not have been
able to insert a string into a MySQL command in php.
Code below works well
$SQL = 'INSERT INTO tb_addressbook (`ID`, `First_Name`, `Last_Name`, `Address`) VALUES (\'24\', \'JJ\', \'Gates\', \'Microsoft\');';
Code below does not work
$SQL = 'INSERT INTO tb_addressbook (`ID`, `First_Name`, `Last_Name`, `Address`) VALUES (\'27\', \''.'"$first"'.'\''.', \'Gates\', \'Microsoft\');';
Can you help?
P.S. Is there a special way to insert a string for numbers?
Hugh
hugh#hahaggerty.com
Try like this :
$SQL = "INSERT INTO tb_addressbook (ID, First_Name, Last_Name, Address) VALUES ('27', '".$first."', 'Gates', 'Microsoft')";

2 MySQL Insert Statements and only the first one runs

I have searched high and low and cannot find anything to fix this problem. apparently my first insert statement runs fine and I can see the changes in the database. The second one fails to update the database even though the script completes. Any help would be greatly appreciated. Thanks in advance.
"INSERT INTO propertyInfo (
districtNumber,
primaryProperty,
platBookPage,
giftedDate,
purchaseDate,
retiredDate,
yearBuilt,
Affiliation,
purchasePrice,
primaryZone,
primaryLandUse,
propertyType,
squareFootage,
soldDate,
soldPrice,
lotSizeSqFt,
iudb,
zoningLandUse,
enterpriseZone,
zoningCode,
florida,
georgia,
Description,
Land,
Development,
acres,
tax,
Name,
granter
)
VALUES (
'$district_number',
'$primary_property',
'$plat_book_page',
'$gifted_date',
'$purchase_date',
'$retired_date',
'$year_built',
'$affiliation',
'$purchase_price',
'$primary_zone',
'$primary_land_use',
'$property_type',
'$square_footage',
'$sold_date',
'$sold_price',
'$lot_size_sqft',
'$iudb',
'$zoning_land_use',
'$enterprise_zone',
'$zoning_code',
'$florida',
'$georgia',
'$description',
'$land',
'$development',
'$acres',
'$tax',
'$name',
'$granter'
)";
$pinksql = "INSERT INTO address (`address`, `address2`, `city`, `state`, `zipCode`, `subDivision`) VALUES ('$address', '$address2', '$city', '$state', '$zip_code', '$sub_division')";

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

PHP database getting variables

I have the following line of code that executes properly except for one hitch. It will print the variable name into the database.
I use this code in one of my scrips:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, \'$first_name\', \'lname\', \'addr\', \'\', \'city\', \'state\', \'zip\', \'ordernum\', \'\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\');";
mysql_query("$sql");
mysql_close($con);
This code prints the followin to the database:
$first_name lname addr city state zip 0 0 0 0 0 0 0 0 0 0 0
Notice that the variable name, and not the contents of the variable are printed. How can I get it to print out the variable contents?
Notice that the variable name, and not the contents of the variable are printed
This is because you are not passing variables to the insert statement, rather you are passing undefined(?) constants; lname, addr, etc. You should pass in the variables you assigned values to: (assuming) $lname, $addr, etc.
Also, you don't need to pass in a NULL for the ID column. If it's set to auto_increment, the database will create this value for you.
You should also take advantage of the default column values defined by your table schema, so you don't end up passing in a huge list of variables with default values, for example, if you have a DEFAULT 0 as part of the schema for item1, item2, item3 etc, you can simply make the following insert:
$sql =
"INSERT INTO `MyDB`.`Shipping` (`FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`) VALUES ('$first_name', '$lname', '$addr', '$city', '$state', '$zip', '$ordernum');";
The database will populate item1, item2, etc columns with 0 for you automatically.
As cambraca mentioned, if you pass variables directly into your query like this, you run the risk of SQL injection. You should read up on how to prepare your queries, which will also force you to use mysqli (vs outdated mysql) api. Or even better, read up on PDO.
For one you have a quoting issue. You seem to have double quotes and then escaped single quotes. don't escape your single quotes if you string is double quoted.
It seems the value of $first_name should work. Is this the exact code? Because if you have single quotes around the whole thing it would create the output you're describing.
All your other columns aren't variables so it's hard to know what you're trying to do. If you aren't going to use them why reference them at all?
In your mysql_query call don't quote $sql again.
Finally check mysql_error() for errors. It could be you are seeing something old in the database and your code isn't working at all.
Consider using PDO. It has support for placeholders, better security and better debugging than the native mysql_* interface.
Change the insertion statement to:
$sql = "INSERT INTO `MyDB`.`Shipping`
(`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`,
`STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`,
`item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`)
VALUES (NULL, '{$first_name}', 'lname', 'addr', '', 'city', 'state',
'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0');";
Also, do check that your $first_name is properly assigned a value.
I suppose not to use inline variables in strings in PHP, and you are escaping ' when you do not need to. Try this:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, '".$first_name."', 'lname', 'addr', '', 'city', 'state', 'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');";
mysql_query($sql);
mysql_close($con);
Rather than using \'$first_name\' replace it with \"$first_name\" and the same follows with other variables too.

Categories