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.
Related
I'm trying to add $_SESSION['user_id'] into a database and, when I echo it in this function, it works fine. However, when I try to push it into my MySQL database, it adds the value 0. Really confused as to why. Thanks for any help!
function fill_team() {
$i = 1;
while ($i < 24) {
$first_name = first_name();
$last_name = second_name();
echo "<br>";
$add_names = mysql_query("INSERT INTO `players` (`first_name`, `last_name`, `user_id`) VALUES ('$first_name', '$last_name', '.$_SESSION['user_id']'.)");
$i++;
}
}
Replace echo $row2['first_name']; with return $row2['first_name'];.
If you want to get some value from the function, you should use return operator to pass the value back. It has nothing to do with printing the value with print or echo.
There's some messy mixed quoting inside the SQL statement:
mysql_query("INSERT INTO `players` (`first_name`, `last_name`, `user_id`)
VALUES ('$first_name', '$last_name', '.$_SESSION['user_id']'.)");
Off the top of my head, I have no idea what SQL this will produce, but this should be written as:
mysql_query("INSERT INTO `players` (`first_name`, `last_name`, `user_id`)
VALUES ('$first_name', '$last_name', '$_SESSION[user_id]')");
or
mysql_query("INSERT INTO `players` (`first_name`, `last_name`, `user_id`)
VALUES ('$first_name', '$last_name', '".$_SESSION['user_id']."')");
public function multiQueryInsert($query){
if($this->conn->multi_query($query)){
do{
$this->conn->store_result();
/*if($result = $this->conn->store_result()){
while($row = $result->fetch_row()){
return $row;
}*/
//$result->free();
//}
$this->conn->more_results();
}
while($this->conn->next_result());
return true;
}
else{
return $this->conn->errno;
}
$this->conn->close();
}
$query = "INSERT INTO `table_name`(`name`, `phone`, `address`, `email`, `cell`, `pcf`, `church`, `group`, `zone`, `dob`, `occupation`, `status`) VALUES ('$names','$phone','$address','$email','$cell','$pcf','$church','$group','$zone','$dob','$occupation','$status')";
$username = explode(' ',$names);
$fname = strtolower($username[0]);
$password = $data;
$query .= "INSERT INTO `table_name2` (`uid`, `pswd`, `Name`, `Email`) VALUES ('$fname','$password','$names','$email')";
if($db->multiQueryInsert($query) === TRUE){
echo '<div class="success">Partner added successfully</div>';
}
else{
die('Error adding partner: '.$db->conn->error);
}
The first code is the method that execute the multi_query while the other codes are the query passed to the method. The error thrown is Error adding partner:
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:
"INSERT INTO `cec_users` (`uid`, `pswd`, `Name`, `Email`) VALUES ('kjvhm,bhjkl','')" at line 1
Try to use semicolon at the end of first insert query like this:
$query = "INSERT INTO `table_name`(`name`, `phone`, `address`, `email`, `cell`, `pcf`, `church`, `group`, `zone`, `dob`, `occupation`, `status`) VALUES ('$names','$phone','$address','$email','$cell','$pcf','$church','$group','$zone','$dob','$occupation','$status');";
I am having an issue with a MySQL query as follows:
My script generates this as an example query:
INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('Test2', '123-456-7890', 'test#test.com', 'mesa', 'az', '04-14-2013')
Which if I drop directly into PHPMyA, works fine. However, the PHP script I am trying to use to send the query from my website is not working and I can't get it figured out. Here it is:
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
mysql_query($sql);
$result = mysql_query($sql);
if($result)
{
echo("<br>Data Input OK");
}
else
{
echo("<br>Data Input Failed");
}
Nothing makes it to the MySQL DB and no PHP errors are displayed, however, if I echo $sql I get the exact query I posted previously.
Just remove the single line mysql_query($sql); on your code and you will be fine.. But you should better start practicing PHP MySQLi which stands for PHP MySQL Improved, such:
$con = mysqli_connect($host, $user, $password, $password);
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysqli_query($con, $sql);
if($result) {
echo("<br>Data Input OK");
} else {
echo("<br>Data Input Failed");
}
$sql = 'INSERT INTO Table_name (`id`, `name`) VALUES ("1", "php");
You are executing $sql twice in your script wich is causing the error, please remove
mysql_query($sql);
And it will be ready to go
I would also suggest to stop using mysql_query please switch to mysqli or PDO
Are you sure there is a valid connection (..mysql_connect())? Try using the full syntax like so..
$conn = mysql_connect(...);
$result = mysql_query($query, $conn);
Also try forcing a commit after you execute the statement -
$mysql_query("COMMIT", $conn);
You are running mysql_query twice. Reason of the error. Try running the following code.
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysql_query($sql) or die(mysql_error());
if($result){
echo("<br>Data Input OK");
} else{
echo("<br>Data Input Failed");
}
use this
"INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$_POST[name]', '$_POST[phone]', '$_POST[email]', '$_POST[city]', '$_POST[state]', '$_POST[date]')";
Try to use mysql_query($sql,$con); instead of mysql_query($sql);.
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$age=$_POST['age'];
$address=$_POST['address'];
$ins="insert into table_name(`name`,`age`,`address`)values('".$name."','".$age."','".$address."')";
mysql_query($ins);
echo 'data inserted successfully';
}
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...
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());