MySQL Text Data Type Too Much? - php

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

Related

insert data by GET

I want insert data by GET in my sql but I can not insert data
<?php
include("config.php");
$f=$_GET["first_name"];
$l=$_GET["last_name"];
$e=$_GET["email"];
$m=$_GET["mobile"];
$b=$_GET["birthday"];
$g=$_GET["gender"];
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES ('$f', '$l', '$e', '$m', '$b', '$g')";
mysqli_query($insert);
?>
I try insert data by this link :
http://localhost:8888/restfull/insert.php?f=hayoo
It's been a long time since I have used mysqli the code below should most likely run though. As others have mentioned never bind unsanitized data (Even if you think you trust the data it's safe to use prepared statements still).
<?php
//Create you db connection
$conn = new mysqli('server', 'user', 'password', 'databasename');
//Create insert statement. Never concat un-sanitized data in statements
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
//Values corespond to ? except the first param which represents format of expected data. "s" stands for string
$stmt->bind_param(
'ssssss',
$_GET["first_name"],
$_GET["last_name"],
$_GET["email"],
$_GET["mobile"],
$_GET["birthday"],
$_GET["gender"]
);
$stmt->execute();
Your url would look like this:
http://localhost:8888/restfull/insert.php?first_name=john&last_name=Doe&email=test#test.com&mobile=0&birthday=May&gender=male
Make sure if you are putting the url above in some type of form you correctly url encode values (I notice many of the values you are collecting will like require it slashes etc).

mysql and php command sometimes doesnt post. Could it be because of my body?

So, I have the following PHP command to post to my db.
$sql = "INSERT INTO `db`.`tab;e` (`id`, `type`, `subtype`, `image1`, `image2`, `image3`, `title`, `body`, `price`, `googlecode`, `date`) VALUES (NULL, '$type', '$subType', '$image1', '$image2', '$image3', '$title', `$body`, '$price', '$googleCode', '$date');";
The data is being grabbed with a post. for instance, the type is
$type = $_POST[type];
etc..
However, when posting stuff, my code sometimes works and sometimes doesnt.
I think its because im using niceEdit to grab the body text and when it posts, Im worried that the ' and the " interfere with my post...
Also, the $googlecode is a bunch of divs with quote marks and others.
Could this be why my code works off and on?
I guess it sometimes failes because you don't escape the values but directly add them to the query. This way some values might break the SQL statement and the statement is vulnerable to SQL injections.
To fix this you have to escape the values or even better, use prepared statements. It is also strongly recommended to add some error handling so you can easier get a meaning full error message (thx Pekka).
foreach($_POST as $key => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$_POST[$key] = mysql_real_escape_string($value);
}
$type = $_POST[type];
//etc...
$sql = "INSERT INTO `db`.`table` (`id`, `type`, `subtype`, `image1`, `image2`, `image3`, `title`, `body`, `price`, `googlecode`, `date`) VALUES (NULL, '$type', '$subType', '$image1', '$image2', '$image3', '$title', '$body', '$price', '$googleCode', '$date');";

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.

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

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

MYSQL ERROR: "You have an error in your SQL syntax"

I have this query running in my PHP script:
$insertQuery = "INSERT INTO blog_articles
VALUES '$title', $tags', '$category', '$blog', '$author', '$date'";
I then run this script:
if ($result = $connector->query($insertQuery)){
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
}
I get this 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 'Title Number 1, General, Blogging, Kayaking, General, Tgis is blog number spelli' at line 2
But I cannot tell what the error is.
You have a single quote missing before $tags.
Your query should be more like this
INSERT INTO blog_articles (`title`, `tags`, `category`, `blog`, `author`, `date`)
VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
You should also look into sanitizing your query. Perhaps this way (but i don't know your exact setup, so results might vary)
$sql = sprintf("INSERT INTO blog_articles (`title`, `tags`, `category`,
`blog`, `author`, `date`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($title), mysql_real_escape_string($tags),
mysql_real_escape_string($category), mysql_real_escape_string($blog),
mysql_real_escape_string($author), mysql_real_escape_string($date));
This uses the sprintf() function, the php documentation has some great examples.
You need to add the names of the fields you are inserting to
INSERT INTO blog_articles ('title', 'tags', 'category', 'blog', 'author', 'date') VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
Also you should add some code to escape double or single quote in your text that could break the SQL query.
use the PHP function mysql_real_escape_string()
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
For more details:
http://uk.php.net/mysql_real_escape_string
As aknock says, you are missing a ' before $tags.
However, you really need to be using mysql_escape_string to protect against SQL injection attacks. Using mysql_escape_string for your SQL query parameters is a good habit to get into.
Using a DB wrapper like PEAR can make escaping parameters much less painful. Your code above could be written like:
$insertQuery = "INSERT INTO blog_articles \
(`title`, `tags`, `category`, `blog`, `author`, `date`) \
VALUES (?, ?, ?, ?, ?, ?)";
$data = array($title, $tags, $category, $blog, $author, $date);
if ($result = $connector->query($insertQuery, $data)) {
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
(assuming $connector is a PEAR DB object)
Explicitly giving the names and order of the columns that you're inserting makes your code much more maintainable and readable. If you change the database schema later, you will be protected from inserting values into the wrong column, or into columns that don't exist any more.

Categories