I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);
Related
ERROR: Could not able to execute
INSERT INTO applications (title, surname, maiden_name, first_name, marital_status, gender, country, date_of_birth, address, email, home_numbers, work_numbers, cell_phone, application_results, next_of_kin_name, next_of_kin_relationship, next_of_kin_number, chronic_disease)
VALUES ('Mr', 'McLaren', '', 'Richard', 'Single', 'Male', 'England', '', 'Room 67 14 Tottenham Court Road London England W1T 1JY', 'mclaren.richard#gmail.com', '020 7946 0072', '020 7946 0549', '020 7946 0760', 'Elizabeth', 'Mother', '020 7946 0831', 'No') ).
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near ')' at line 6
The php code is:
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "cas");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$title = mysqli_real_escape_string($link, $_REQUEST['title']);
$surname = mysqli_real_escape_string($link, $_REQUEST['surname']);
$maiden_name = mysqli_real_escape_string($link, $_REQUEST['maiden_name']);
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$marital_status = mysqli_real_escape_string($link, $_REQUEST['marital_status']);
$gender = mysqli_real_escape_string($link, $_REQUEST['gender']);
$country = mysqli_real_escape_string($link, $_REQUEST['country']);
$date_of_birth = mysqli_real_escape_string($link, $_REQUEST['date_of_birth']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$home_number = mysqli_real_escape_string($link, $_REQUEST['home_number']);
$work_number = mysqli_real_escape_string($link, $_REQUEST['work_number']);
$cell_phone = mysqli_real_escape_string($link, $_REQUEST['cell_phone']);
$next_of_kin_name = mysqli_real_escape_string($link, $_REQUEST['next_of_kin_name']);
$next_of_kin_relationship = mysqli_real_escape_string($link, $_REQUEST['next_of_kin_relationship']);
$next_of_kin_number = mysqli_real_escape_string($link, $_REQUEST['next_of_kin_number']);
$chronic_disease = mysqli_real_escape_string($link, $_REQUEST['chronic_disease']);
// attempt insert query execution
$sql = "INSERT INTO applications (title, surname, maiden_name, first_name, marital_status,
gender, country, date_of_birth, address, email, home_numbers, work_numbers, cell_phone,
application_results, next_of_kin_name, next_of_kin_relationship, next_of_kin_number, chronic_disease)
VALUES ('$title', '$surname', '$maiden_name', '$first_name', '$marital_status',
'$gender', '$country', '$date_of_birth', '$address', '$email', '$home_number', '$work_number', '$cell_phone',
'$next_of_kin_name', '$next_of_kin_relationship', '$next_of_kin_number', '$chronic_disease') )";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Your INSERT statement had an extra bracket at the end of sentence.
INSERT INTO .... '$chronic_disease') >)< ';
INSERT syntax
INSERT INTO table(columns) VALUES(values)
$sql = "INSERT INTO applications (title, surname, maiden_name, first_name, marital_status,
gender, country, date_of_birth, address, email, home_numbers, work_numbers, cell_phone,
application_results, next_of_kin_name, next_of_kin_relationship, next_of_kin_number, chronic_disease)
VALUES ('$title', '$surname', '$maiden_name', '$first_name', '$marital_status',
'$gender', '$country', '$date_of_birth', '$address', '$email', '$home_number', '$work_number', '$cell_phone',
'$next_of_kin_name', '$next_of_kin_relationship', '$next_of_kin_number', '$chronic_disease')";
You had a extra ) at the end of the above statement.
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
I'm on ubuntu running on apache2.
<?php
$con = mysqli_connect("localhost", "root", "password", "loops");
if (!mysqli_connect_errno()) {
echo "Error to connect: ".mysqli_connect_error();
}
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
echo "First: ".$firstName."<br />Age: ".$age;
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values (".$firstName.",".$lastName.",".$age.")";
if (!mysqli_query($con)) {
die("Error :".mysqli_error($con);
}
echo "1 added";
mysqli_close($con);
?>
I don't know what to do now, but the error seems to be on the '$sql', 'cause when I put that
under a comment, the rest works...
You forgot the infamous mistake of wrapping the varchar variables with single quote '
"INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
Additionally, It's highly risky for you, not be using protections against SQL Injections
Try this, mysqli_query($con, $sql) You need to execute the query so that it will store into the database
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
if (!mysqli_query($con, $sql)) {
...................^
die("Error :".mysqli_error($con);
}
Try this:
$sql = "INSERT INTO persons (`FirstName`, `LastName`, `Age`) values (".$firstName.",".$lastName.",".$age.")";
If this doesn't work, what error do you get.
I'm a complete noob to PHP and working with mysql so you know I do however have a great deal of experience with HMTL and CSS. All I need is for a form on my site to upload the information in the form to my database. The problem is that clicking the "submit" button just opens up a blank tab with the address of my .php file in it and displays a blank white screen. The .php is below.
<?php
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
$sql = "INSERT INTO $usertable (firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
$sql="INSERT INTO $usertable (firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('".$_POST[firstName]."', '".$_POST[lastName]."', '".$_POST[streetAddress]."', '".$_POST[city]."', '".$_POST[state]."', '".$_POST[zip]."', '".$_POST[country]."', '".$_POST[email]."', '".$_POST[phone]."', '".$_POST[badgeName]."')";
?>
Now from what I've read this is usually caused by some kind of error in the code. This is difficult for me as I don't know PHP very well and almost everything in the page was taken from other peoples code. Most of it from the code helps from godaddy.com (where the site and database are hosted).
I've tested to make sure that PHP is supported and enabled and it is. I have a form mailer that already functions just fine. I have setup a DNS, I have tried multiple different syntaxes, I have called tech support to see if it is something on their end, I've migrated my sites from windows to linux and every thing I change results in the exact same blank white screen. I have no doubt that after all this it's going to be something that's stupidly easy to fix or blatantly obvious but if anybody could take a look and see what I'm missing I would be very grateful.
My new code after taking in some of the answers posted. I'm still getting a NOTICE and it's still not inserting anything into my database.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
//connect to mysql
$link_id = mysql_connect($hostname, $username, $password);
if (!$link_id) {
die("Unable to connect to database! Please try again later. error:".mysql_errno());
}
//make sure your DB exists
if (!mysql_select_db($dbname)) die ("Connected to mysql but could not connect to the DB. error:".mysql_errno());
//avoid sql_injection
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$streetAddress = mysql_real_escape_string($_POST['streetAddress']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip = mysql_real_escape_string($_POST['zip']);
$country = mysql_real_escape_string($_POST['country']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$badgeName = mysql_real_escape_string($_POST['badgeName']);
//write the query
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
//then you'll need to execute the query :)
mysql_query($sql);
?>
From what I can tell, this code just connects to a database and sets a variable $sql. Are you actually executing the query anywhere? Are you doing anything to print something on the screen?
$_POST[firstName] should be $_POST['firstName'] and so on and
mysql_query($sql) or die('MySQL Error: ', mysql_error());
echo 'Data inserted';
You shouldn't not be using mysql_ now, its deprecated. Do it with PDO
first of all
$_POST[firstname] should be $_POST['firstname']
third
mysql_query($sql,$conn);
second
$conn=mysql_connect(your parameters);
Include this two lines at the very top of your php code:
error_reporting(E_ALL);
ini_set('display_errors', '1');
It is going to enable error reporting and so you will be able to debug your script.
Maybe the problem is that the reading of $_POST variables (and of any array type variable) should be made with 'quotes' when using string index names:
$_POST[firstName] must be written as follows:
$_POST['firstName']
A good way of making this query more secure (against sql injection attacks for example) is to scape the values in POST instead of passing it directly to the query.
$firstName = mysql_real_escape_string($_POST['firstName']);
The value in POST will be scaped so you can pass it to your SQL.
Try to make that will all your variables:
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
Finally you need to actually execute the query:
mysql_query($sql);
If it goes ok you'll see no errors, but be shure to enable error reporting to this script. When everything it's ok remember to remove the error reporting.
Like the other guys said, put the comments in the array reference. That being said you really need to escape the $_POST variables to avoid SQL Injection, its also easier to debug if the code is clearly ordered :)
With ordered code you can type echo "some text"; at any touch point you want to so you can see where the code breaks.
Also switching on error reporting in your php.ini or in code (http://php.net/manual/en/function.error-reporting.php) would be the best bet for watching the errors that you can't predict.
<?php
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
//connect to mysql
$link_id = mysql_connect($hostname, $username, $password);
if (!$link_id) {
die("Unable to connect to database! Please try again later. error:".mysql_errno());
}
echo "connected to mysql";
//make sure your DB exists
if (!mysql_select_db($dbname)) die ("Connected to mysql but could not connect to the DB. error:".mysql_errno());
echo "connected to database";
//avoid sql_injection
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$streetAddress = mysql_real_escape_string($_POST['streetAddress']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip = mysql_real_escape_string($_POST['zip']);
$country = mysql_real_escape_string($_POST['country']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$badgeName = mysql_real_escape_string($_POST['badgeName']);
echo "sanitised input";
//write the query
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
echo "build query: ".$sql;
//then you'll need to execute the query :)
if (mysql_query($sql))
echo "query success";
else
echo "query failed";
//ps you can ignore the last? >
When my form is submitted (via Ajax), I'm getting the following error message:
[17-Oct-2012 11:46:29] PHP Warning: mysqli_query() [<a href='function.mysqli-query'>function.mysqli-query</a>]: Empty query in /home1/xenongro/public_html/testing/enrolment/thanks.php on line 32
I have a suspicion that it's something to do with the if/else statements, but not sure what the actual problem is.
Can anyone help?
<?php
$firstname = htmlspecialchars(trim($_POST['fname']));
$lastname = htmlspecialchars(trim($_POST['lname']));
$worktel = htmlspecialchars(trim($_POST['worktel']));
$dbc = mysqli_connect('localhost', 'xxxxx', '<xxxx>', 'xxxx')
or die ('Could not connect to MySQL server.');
if ($level != "IOSH Managing Safely"){
if ($funding == "Self Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
else if ($funding == "Employer Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
}
else if ($level == "IOSH Managing Safely"){
if ($funding == "Self Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
else if ($funding == "Employer Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
}
$result = mysqli_query($dbc, $query)
or die ('error querying database');
mysqli_close($dbc);
?>
try
var_dump($query);
var_dump($funding);
just before
$result = mysqli_query($dbc, $query);
it'll give you more information
I suspect that $funding might have slight variation to your constant strings
might be typo / extra space / cap case
There are two situation where no query is being set:
the level does not match the string, or the funding does not match the string.
It might be a problem with the spaces.
Worse, you don't use mysql_real_escape_string and unless magic_quotes_gpc is on, this allows an attacker to inject his SQL.
$funding doesn't appear to be defined in the code example provided, so none of your if's will match.