inserting data into 2 tables at once - php

I am wondering how can I insert the values retrieved from a HTML form into 2 tables, loginDetails and memberDetails.
loginDetails (table_1 shown in the code)
loginID (PK) <-- auto increment
username
password
memberDetails (table_2 shown in the code)
memberID (PK) <-- auto increment
loginID (FK)
These are the codes I have so far, however the loginID in memberDetails table are always 0,:
PHP codes
$Query = "INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username']."',
'".$formValue['password']."')";
if (mysqli_query($Link, $Query)) {
$lastID = mysql_insert_id();
$Query2 = "INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')";
if (mysqli_query($Link, $Query2)) {
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query));
}
else {
$message = "Error occur in query2";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
}
else {
$message = "Error in query1";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
It would be great if this question can be solved, as i have been struggling in this for 3 nights already. Cheers.

You can place your queries in an array. Loop through the array. If an error occurs, exit the script.
$myQueries = array(`"INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username'].",
'".$formValue['password']."')",
"INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')"
)`;
for($i = 0; $i < count($myQueries); $i++){
if (mysqli_query($Link, $myQueries[$i])) {
$lastID = mysql_insert_id();
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true',
'action'=>'login',
'html'=>$message,
'console.log'=>$Query));
}
else {
$message = "Error occur in query[$i]";
echo json_encode(array('action'=>'error',
'html'=>$message,
'console.log'=>$Query));
exit; // stops the next query
}
}
}

Related

MySQL affected rows -1 when inserting data into database

I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"

Inserting a statement requiring minimum number of characters

Here I have a code which inserts data into db. It's working fine now, but I want the title to have a minimum of 4 characters and the body a minimum of 500.
Here is my code:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if ($title && $body && $category) {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}else {
echo "data missing";
}
}
?>
I tried the code below to put minimum requirements for the title and body, but it echoes the title error message whenever you submit data even when the title contains more than 5 characters.
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title<5)) {
echo "Title must be of minimum 5 characters";
}
else {
if (strlen($body<500)) {
echo "Title must be of minimum 500 characters";
}
else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}
}
}
?>
A question as such deserves an explanation for future readers to the question.
The reason why your code is failing, is that:
if (strlen($title<5))
evaluates to:
function($string conditional)
when the syntax is:
function($string) conditional
The manual states:
int strlen ( string $string )
http://php.net/manual/en/function.strlen.php
Example pulled from the manual:
if (strlen($foo) === 0) echo 'Null length is Zero <br>';
Plus, as stated in comments. Your query is subject to an SQL injection. It's best to use a prepared statement.
Consult the following links:
How can I prevent SQL injection in PHP?
https://en.wikipedia.org/wiki/Prepared_statement
I think the issue lies with the conditions you used.
if (strlen($title<5))
should be
if (strlen($title)<5)
similarly
if (strlen($body<500))
to be
if (strlen($body)<500)
Try this:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title) < 5) {
echo "Title must be of minimum 5 characters";
}else {
if (strlen($body) <500 ) {
echo "Body must be of minimum 500 characters";
}else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}else {
echo "error";
}
}
}
}
?>

Message dialog if PHP function successful or not

I have a PHP function that checks some data before inserting it into the DB.
For now I have thees messages that inside my php function that display, wherever I am calling the function. ex: div.
I would like instead of the small message inside the div, to have a message box that will display the message. How can I do this? Thanks
if($u_l_name == $dbuser_last_name and $u_name == $dbuser_first_name)
{
echo "Record Exists Already";
}
else
{
$stmt2 = $this->link->prepare("INSERT INTO employers (user_password, user_first_name, user_last_name, user_DOB, user_address, user_email, user_phone, user_gender, user_position, user_contract_type, user_contract_hours) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt2->bind_param("ssssssssssi", $u_password, $u_name, $u_l_name, $u_DOB, $u_address, $u_email, $u_phone, $u_gender, $u_position, $u_contract_type, $u_contract_hours);
$stmt2->execute();
$stmt2->close();
echo "Record Added Succesfully";
}
Function call:
<?php
if(isset($_POST['submitButton']))
{
$admin_query->addEmployerData($u_password, $u_name, $u_l_name, $u_DOB, $u_address, $u_email, $u_phone, $u_gender, $u_position, $u_contract_type, $u_contract_hours);
}
?>
Do you mean Javascript alert method? if yes here is how you can do it:
$message;
if($u_l_name == $dbuser_last_name and $u_name == $dbuser_first_name)
{
$message = "Record Exists Already";
}
else
{
$stmt2 = $this->link->prepare("INSERT INTO employers (user_password, user_first_name, user_last_name, user_DOB, user_address, user_email, user_phone, user_gender, user_position, user_contract_type, user_contract_hours) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt2->bind_param("ssssssssssi", $u_password, $u_name, $u_l_name, $u_DOB, $u_address, $u_email, $u_phone, $u_gender, $u_position, $u_contract_type, $u_contract_hours);
$stmt2->execute();
$stmt2->close();
$message = "Record Added Succesfully";
}
echo "<script>alert('$message')</script>";

Update successfully but couldn't update into DB

I couldn't find any error. I tried the query on phpmyadmin and it works well but when I do in php page, it couldn't update into DB. The following code below:
$registerID = ($_POST['registerID']);
$firstName = ucwords(htmlspecialchars($_POST['firstName']));
$lastName = ucwords(htmlspecialchars($_POST['lastName']));
$emailAddress = htmlspecialchars($_POST['emailAddress']);
$mainAddress = ucwords(htmlspecialchars($_POST['fullAddress']));
$updateCity = ucwords($_POST['userCity']);
$updateCountry = $_POST['userCountry'];
$postalCode = strtoupper(htmlspecialchars($_POST['userZip']));
$profilePic = $_POST['pic'];
$updateProf = " UPDATE register_user
SET firstName='$firstName',
lastName='$lastName',
emailAddress='$emailAddress',
mainAddress='$mainAddress',
registerCity='$updateCity',
registerCountry='$updateCountry',
postalCode='$postalCode'
WHERE registerID = '$registerID'";
if (mysqli_query($mysqli, $updateProf)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
In the end, there are no errors after I updated on the webpage, it just show Record updated successfully. But it didn't update into DB. Any ideas?
UPDATED CODING
$checkProfile = "SELECT * FROM register_user where emailAddress = '$emailAddress'";
$editProfile = mysqli_query($mysqli,$checkProfile);
if ($editProfile) {
if (mysqli_num_rows($editProfile) > 0) {
header("Location: event?error=That name of email has already been taken");
} else {
$updateQuery = "UPDATE register_user
SET firstName = '$firstName',
lastName = '$lastName',
emailAddress = '$emailAddress',
mainAddress = '$mainAddress',
registerCity = '$updateCity',
registerCountry = '$updateCountry',
postalCode = '$postalCode'
WHERE registerID = '$registerID'";
$updateResult = mysqli_query($mysqli,$updateQuery);
header("Location: profileUser");
}
}
After I updated, it still doesn't work after I am using prepared statement. Any ideas?
Try executing the query first, saving it into a variable.
then, check if the query executed by doing:
if(!$query) echo "Query error : " . $mysqli->error;
This will give you more detailed error report.

empty field to mysql using php

i have code for save 3 textbox in one field in databse
no problem when i am enter 3 textbox , but when i fill 1 textbox and press ok
save another textbox in database as blank
i want just take the textbox is fulled and ignore the textbox empty
this is my code
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$result3=mysql_query($sql3);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
Execute your sql query only the variable value not equal to empty.
try this,
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if ($expert_name != "") {
$sql = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result = mysql_query($sql);
}
if ($expert_name2 != "") {
$sql2 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2 = mysql_query($sql2);
}
if ($expert_name != "") {
$sql3 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 = mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if ($result || $result2 || $result3) {
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
You should also check $result2 and $result3. I added that in this answer
try this
if ( !empty($_POST['expert_name']) ){
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if ( !empty($_POST['expert_name2']) ){
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if ( !empty($_POST['expert_name3']) ){
$sql3 ="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 =mysql_query($sql3 );
}
Then you might want to check if the variable is empty().
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if(!empty($expert_name)) {
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if(!empty($expert_name2)) {
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if(!empty($expert_name3)) {
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3=mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
Also note: You only check if $result is okay. If you only fill textbox 2 and leave 1 empty, the value of 2 it will get inserted but an error is shown.
I'd say your code need general review, but as it is for now you will have to do something like this each query:
if (!empty($expert_name2){
$result2=mysql_query($sql2)
}
But you should try to loop your queries in foreach rather than manually write every on query. And by the way:
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
This code only return succes when 1st wuery success because you use $result which is set in 1st query only
The ID is probably NOT NULL AUTO_INCREMENT, so that won't accept NULL as value.
try sending blank value, such as:
$sql="INSERT INTO experts(id,expert_name) VALUES ('', '$expert_name')";
Also, build bulk insert, rather than multiple.
I will explain why, when you insert single insert into the database, the values being inserted, then, the DB engine flushes indexes (they written to disk), unless you have set delay_key_write=ALL in you my.cnf. Index flushing directly affects your db performance.
Please, check the reworked code out. The code adjusted for bulk insert, sql string escaping for security purposes and additional verification for post keys existence.
<?php
include("connect.php");
// this is for arabic language.
mysql_query("SET NAMES utf8");
$values = array();
$skipInsert = true;
$fields = array('expert_name', 'expert_name2', 'expert_name3');
$insert = "INSERT INTO experts(id,expert_name) VALUES ";
// Loop through predefined fields, and prepare values.
foreach($fields AS $field) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$values[] = "('', '".mysql_real_escape_string(trim($_POST[$field]))."')";
}
}
if(0 < sizeof($values)) {
$skipInsert = false;
$values = implode(',', $values);
$insert .= $values;
}
if(false === $skipInsert) {
mysql_query($insert);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful","<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR","<br>",mysql_error(),"<a href='expert_add.php'><br>Please try again </a>";
}
HTH,
VR
if(!empty($textbox1_value)) {
//DO SQL
}
You can repeat this for multiple boxes however you wish, the empty operator checks if its empty, so if its not empty the "//DO SQL" area will get run.

Categories