I've been reading and gathering information for 2 days already and I give up. I have no clue why my piece of simple code is not succeeding.
I want to insert data from one form into two tables and YES I know there are exactly same problems described here and there, but as I said I'm familiar with them and also need to ask more questions.
The problem is in my query somewhere, at least this is what I believe it is.
Here it goes:
unset($err);
//Variables
$host = 'my.server.com';
$user = '123';
$pass = 'password';
$dbname = '123';
$err = array();
$error_form = false;
$img = "sth/sth.jpg";
//Connecting to the database using mysqli application programming interface
$con = mysqli_connect($host, $user, $pass, $dbname);
if (!validate()) {
if (!$con) {
echo "Connection failed : <br />" . $new_con->connect_errno . "<br />" . $new_con->connect_error;
exit;
} else {
echo "Connected! <br />";
}
var_dump($name);
echo "<br />";
var_dump($email);
echo "<br />";
var_dump($img);
echo "<br />";
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
echo "<br />";
$_POST["name"] = "";
$_POST["email"] = "";
$_POST["story"] = "";
}
//Form validation
function validate() {
global $name, $email, $story, $err, $error_form;
if($_SERVER['REQUEST_METHOD']=="POST") {
if(isset($_POST["name"]) && !empty($_POST["name"])) {
$name = htmlspecialchars($_POST["name"]);
} else {
$err[0] = "Name is missing.";
$error_form = true;
}
if(isset($_POST["email"]) && !empty($_POST["email"])) {
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$email = htmlspecialchars($_POST["email"]);
} else {
$err[1] = "Email was verified as incorrect.";
$error_form = true;
}
} else {
$err[1] = "Email is missing.";
$error_form = true;
}
if(isset($_POST["story"]) && !empty($_POST["story"])) {
$story = htmlspecialchars($_POST["story"]);
} else {
$err[2] = "Your story does not contain any characters, it can't be submited.";
$error_form = true;
}
}
return $error_form;
}
Everything what confuses me happens here:
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
I've tried to SELECT the id FROM the table1 table and SET it as a #value instead of LAST_INSERT_ID(). I've tried to run two queries...many different solutions.
I found out when I dump mysqli_query($con,$query) it gives false every time unless I don't use transaction, so just simple queries, but I need them.
Last thing is should I use PDO instead of mysqli? Why?
and
Why to use mysqli object oriented style instead of procedural one?
Every help is appreciated. I would like more to understand than just to achieve the effect here.
Be aware this is my first post here, but not the first visit.
You can only do one query at a time with mysqli_query Look at mysqli_multi_query()
http://www.w3schools.com/php/func_mysqli_multi_query.asp
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_multi_query($con,$query));
Related
I'm trying to insert some data with PHP, but I have this problem with the following model not inserting the data into the SQL database. The controller sends the data correctly, I checked and is also received in the model(also checked), but the query is not working, the data is not inserted in the database. Can you help me?
This is the controller:
<?php
try {
$name = "Frank";
$lname = "Casttle";
$email = "frankcastle#email.com";
$mobile = "3136556195";
// $name = htmlspecialchars($_POST['name']);
// $lname = htmlspecialchars($_POST['lname']);
// $email = htmlspecialchars(trim($_POST['mail']));
// $mobile = htmlspecialchars(trim($_POST['phone']));
require_once ("../model/connection.php");
require_once ("../model/handle_data_model.php");
$connection = Connect::connection();
$handleUser = new Handle_users($connection);
$insertUser = new Users_obj();
if(empty($name) || empty($lname) || empty($email) || empty($mobile)) {
echo "<b class='text-danger'>¡You must complet all required fields!<b>";
} else {
$insertUser->set_name(mb_strtolower($name));
$insertUser->set_lname(mb_strtolower($lname));
$insertUser->set_email(mb_strtolower($email));
$insertUser->set_userMobile($mobile);
// echo "<b class='text-danger'>¡Data Sent!<b>";
$handleUser->set_basicUser($insertUser);
}
} catch(exception $e) {
// die ("Error: " . $e->getMessage());
die ();
echo "<b class='text-danger'>1. ".$e->getMessage()."<b>)";
}
?>
This is the model:
<?php
public function set_basicUser(Users_obj $setUser) {
$name = $setUser->get_name();
$lname = $setUser->get_lname();
$email = $setUser->get_email();
$mobile = $setUser->get_userMobile();
echo $name." ".$lname." ".$email." ".$mobile ; // Data is arriving correctly
$this->connection->beginTransaction();
try {
$insert_persona = "INSERT INTO usuario (name, lname, mail, phone) VALUES
('".$name."', '".$lname."', '".$email."', '".$mobile."')";
$this->connection->exec($insert_persona);
echo "<b class='text-primary'>2. ¡User Inserted!<b>";
} catch (PDOexception $e) {
$this->connection->rollback();
echo "<b class='text-danger'>3. ".$e->getMessage()."<b>)";
}
$this->connection = null;
}
?>
At the end, the code enters in the try and execute the code, the transaction is succesful, even it didn't throw error, but the model is not inserting the data into the database. Can you help me? Maybe I'm missing something. Thank you!
I am trying to input data to MySQL using PHP. Don't know what's wrong. The connection succeeds, no errors but at the end there is not data being written to the database.
$dbhost = "localhost";
$dbname = "listings";
$un = $_POST["un"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$des = $_POST["des"];
$quan = $_POST["quantity"];
$specs = $_POST["specs"];
$price = $_POST["price"];
$url1 = ".";
$url2 = ".";
$url3 = ".";
$url4 = ".";
$connection = mysqli_connect($dbhost,$un,$pass,$dbname);
if (!$connection) {
die("Error".mysqli_error);
} else {
echo "Database connection successfull ".$des;
}
$query = "INSERT INTO items
(name,description,quantity,specs,price,url1,url2,url3,url4) VALUES
'$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')
";
echo "Hellos";
$exeute_query = mysqli_query($query,$connection);
if(!execute_query){
die("error ".mysqli_error());
echo "query error";
} else {
echo "Query successfull";
}
mysqli_close($connection);
Any help?
There are several small mistakes in your code:
$query = "INSERT INTO items (name,description,quantity,specs,price,url1,url2,url3,url4) VALUES ('$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')";
echo "Hellos";
**$exeute_query** = mysqli_query($query,$connection); // $execute_query instead of $exeute_query
if(!**execute_query**){ //$execute_query instead of execute_query
die("error ".mysqli_error());
echo "query error";
}
else{echo "Query successfull";}
mysqli_close($connection);
?>
Your code breaks at the if statement because no fucntion with that name is found (if you do not use the dollarsign to show it is a variable, php will interpret it as a function. Also, when initiating your variable you forgot a 'c' so make sure to check if you have the correct variable name or php won't find your variable. Now your query will work or give an error message in case of wrong data formats or bad connection. Use code listed below to debug your php in the future.
error_reporting(E_ALL);
ini_set('display_errors', 'On');
I kinda ran into a problem with my form which is connected with the DB through the outdated MySQL. I'm trying to convert this to MySQLi following online sources and my own knowledge but it doesn't seem to do the trick. I have checked stackoverflow (How to solve Mysql to mysql as I have some problems) which does cover the convertion for some points but as I have some extra functions I dont quite know how to go. Also, is the striplashes function still necessary when using MySQLi? Your help and time is much appreciated, the script goes as follow:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = false;
if(empty($_POST['formName']))
{
$errorMessage = true;
}
if(empty($_POST['formEmail']))
{
$errorMessage = true; }
if(empty($_POST['formAddress']))
{
$errorMessage = true; }
if(empty($_POST['formPrice']))
{
$errorMessage = true; }
$varName = $_POST['formName'];
$varEmail = $_POST['formEmail'];
$varAddress = $_POST['formAddress'];
$varPrice = $_POST['formPrice'];
$varComments = $_POST['formComments'];
if($errorMessage == false)
{
$db = mysql_connect("","","");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("" ,$db);
$sql = "INSERT INTO formdata (name, email, address, price, comments) VALUES (".
PrepSQL($varName) . ", " .
PrepSQL($varEmail) . ", " .
PrepSQL($varAddress) . ", " .
PrepSQL($varPrice) . ", " .
PrepSQL($varComments) . ")";
mysql_query($sql);
header("Location: thankyou.php");
exit();
}
}
//sql injection protection..
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
I had the connecting part working but It didnt write to the DB so I think the query part went wrong.
Just basic changes :
$link = mysqli_connect('localhost','root','pass','myDB');
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
$sql= "INSERT INTO keypairs (name, email, address, price, comments) VALUES ('$varName','$varEmail','$varAddress','$varPrice','$varComments')";
if (!mysqli_query($link,$sql)) {
//error ...
}
final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function
UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.