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';
}
Related
I know inserting into multiple tables with single query is not possible,
now I am trying to insert into 2 tables with php using START TRANSACTION but its not working.
my sql query is looks like
mysqli_query($con,"START TRANSACTION
INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '$fname', '$lname', '$domain', '$address1', '$address2', '$city', '$country', '$region', '$zip', '$phone', '$getplan', '$duration', '$getprice', '', '0', '0', '$code', '$date', '$time','0', '', '')
INSERT INTO domains (username) VALUES ('$getuser') COMMIT");
So where is the problem??
many thanks in advance.
it is because mysqli_query can handle only one comand each time. Split them like:
mysqli_query($con, "SET AUTOCOMMIT=0");
mysqli_query($con,"START TRANSACTION");
$insert1 = mysqli_query($con,"INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '$fname', '$lname', '$domain', '$address1', '$address2', '$city', '$country', '$region', '$zip', '$phone', '$getplan', '$duration', '$getprice', '', '0', '0', '$code', '$date', '$time','0', '', '')");
$insert2 = mysqli_query($con,"INSERT INTO domains (username) VALUES ('$getuser')");
if($insert1 && $insert2) {
mysqli_query($con,"COMMIT");
} else {
mysqli_query($con,"ROLLBACK");
}
mysqli_query($con, "SET AUTOCOMMIT=1");
update: if you are using mysqli the objectorientated way, you can do the following:
$mysqli->begin_transaction();
$insert1 = $mysqli->query("INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '$fname', '$lname', '$domain', '$address1', '$address2', '$city', '$country', '$region', '$zip', '$phone', '$getplan', '$duration', '$getprice', '', '0', '0', '$code', '$date', '$time','0', '', '')");
$insert2 = $mysqli->query("INSERT INTO domains (username) VALUES ('$getuser')");
if($insert1 && $insert2) {
$mysqli->commit();
} else {
$mysqli->rollback();
}
HINT: if you use an older PHP version as 5.5.0, you can't use $mysqli->begin_transaction(); and have to use $mysqli->autocommit(false); at the begining and $mysqli->autocommit(true); at the end instead
Instead of
if($insert1 && $insert2)
name it just "insert" and then:
if ($insert->affected_rows > 0)
I have put together what I think is a simple addition to a php form-processing script (to insert data in a database, after sending it through to an email).
For some reason, I always get the error message, and the actual input of the data never gets through to the database. I've added the query to the output, and all the received values seem alright.
Thanks in advance.
// username, passw, database are all defined earlier in code.
// all the variables are taken out of form inputs (and they all arrive fine by email.
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
//inserting data order
$order = "INSERT INTO flights('restime', 'flyfrom', 'flyto', 'dateoutbound', 'outboundflex', 'datereturn', 'returnflex', 'pax', 'klasse', 'name', 'email', 'phone', 'comments', 'status') VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
echo $order;
}
Thanks a lot in advance.
Database configuration setting must be like below
$link=mysql_connect(localhost,$username,$password);
#mysql_select_db($database,$link) or die( "Unable to select database");
After this you can write your insert query and etc....
You should not use the single quotes for fields in the query. if you use the backticks, then you don't get error. Just like the following
You must use the mysql_error() function to check the error in the query. Check the below code.
I have found one more issue. You have to use single quotes around the hostname in mysql_connect function. This also may cause error.
I have used the following code. It is working fine for me.
<?php mysql_connect('localhost','root','');
#mysql_select_db('test') or die( "Unable to select database");
//inserting data order
$order = "INSERT INTO testone (`restime`, `flyfrom`, `flyto`, `dateoutbound`, `outboundflex`, `datereturn`, `returnflex`, `pax`, `klasse`, `name`, `email`, `phone`, `comments`, `status`) VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
//declare in the order variable
$result = mysql_query($order) or die(mysql_error()); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
echo $order;
}
error is in this query :
$order = "INSERT INTO flights('restime', 'flyfrom', 'flyto', 'dateoutbound', 'outboundflex', 'datereturn', 'returnflex', 'pax', 'klasse', 'name', 'email', 'phone', 'comments', 'status') VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
You are using ' in-spite of using ` for the column name in the table.
use this query and i am sure it will run great
$order = "INSERT INTO testone (`restime`, `flyfrom`, `flyto`, `dateoutbound`, `outboundflex`, `datereturn`, `returnflex`, `pax`, `klasse`, `name`, `email`, `phone`, `comments`, `status`) VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
:)
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 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.
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...