php mysqli insert data into two tables - php

I'm trying to insert data into 2 tables in php mysqli but it inserts data in the first table fine but not inserting anything in the second where there are other columns as well in the second table.
Here is my code:
$sql = "INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES ('$stnam', '$stage', '$stdob', '$stgen', '$styer', '$stGr', '$stadd')";
$sql1 = "INSERT INTO parta (name, stgroup, year) VALUES ('$stnam', '$stGr', '$styer')";
$result = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql1);
Is anything wrong in the above code? Any suggestions?

I can't really see what's exactly wrong with your code, it might happen that some of the columns on the parta table are not supposed to be null. With the code you provided, it's hard to tell, as there's no error handling at all. You might want to use transactions, then use proper error handling and also use prepared statements.
Try with this code that I have prepared for you.
<?php
$con = new mysqli("..."); // you should know this part already
$success = false;
try {
$con->autocommit(FALSE);
$con->begin_transaction();
if ($sql = $con->prepare("INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES (?,?,?,?,?,?,?)")) {
$sql->bind_param('sissss', $stnam, $stage, $stdob, $stgen, $styer, $stGr, $stadd);
if (!$sql->execute()) {
throw new Exception($sql->error);
}
if ($sql_two = $con->prepare("INSERT INTO parta (name, stgroup, year) VALUES (?,?,?)")) {
$sql_two->bind_param('sss', $stnam, $stGr, $styer);
if (!$sql_two->execute()) {
throw new Exception($sql_two->error);
}
}
}
if ($con->commit()) {
$success = true;
} else {
throw new Exception('Transaction commit failed...');
}
}catch (Exception $ex) {
try {
// something went wrong,rollback and display message
$con->rollback();
echo $ex->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
}
$con->autocommit(TRUE);
if ($success) {
echo "data successfully inserted";
}
?>

Try this. It could be because you have the same variable name for two different actions. I've just rename the second result as $result1
$sql = "INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES ('$stnam', '$stage', '$stdob', '$stgen', '$styer', '$stGr', '$stadd')";
$sql1 = "INSERT INTO parta (name, stgroup, year) VALUES ('$stnam', '$stGr', '$styer')";
$result = mysqli_query($con, $sql);
$result1 = mysqli_query($con, $sql1);

Related

How last_id works?

The customer sql is inserted the others are not. Help. Thanksss
I have sql for customer_tbl, transaction_tbl, and order_tbl.
customer_no, transaction_no and orderlist_no are A_I.
This is my code so far.
$x=0;
while ($x!=5) {
$product_sku[$x] = $_POST['productsku[$x]'];
$quantity[$x] = $_POST['productqty[$x]'];
$x=$x+1;
}
$sqlc = "INSERT INTO customer_tbl(customer_name, fb_url, mobile_no, email_address, address) VALUE ('$customer_name', '$fb_url', '$mobile_no', '$email', '$address');";
mysqli_query($conn, $sqlc);
$last_id = mysqli_insert_id($conn);
$sqlt = "INSERT INTO transaction_tbl(customer_no, transaction_type, status, transaction_date, deadlinepay_date, payment_mode, delivery_option) VALUE ('$lastid', 'OL-', '1', CURRENT_TIMESTAMP(), '$deadlinepay_date', '$payment_mode', '$shipping_option');";
mysqli_query($conn, $sqlt);
$last_id = mysqli_insert_id($conn);
$x=0;
while ($x!=5) {
if (!empty($product_sku[$x])) {
$sqlo = "INSERT INTO order_tbl(transaction_no, product_sku, quantity) VALUES ('$last_id', '$product_sku', '$quantity');";
mysqli_query($conn, $sqlio);
}
$x=$x+1;
}
In your code, you have $last_id = mysqli_insert_id($conn); but in your query, you have ...VALUE ('$lastid'....
So change $lastid to $last_id or the other way around.
You should keep naming your variables consistent to avoid confusion in the future.

How to check if a table exists in MySQL using PHP PDO? [duplicate]

This question already has answers here:
Check if MySQL table exists without using "select from" syntax?
(19 answers)
Closed 5 years ago.
if($count <= 0 ) // IF TABLE DOES NOT EXIST -> CREATE AND INSERT DATA
{
$CREATE_TABLE= "CREATE TABLE $TABLE_NAME LIKE student; INSERT $TABLE_NAME SELECT * FROM student;";
$created = $connect->exec($CREATE_TABLE);
if($created!=FALSE)
{
$SQL = "INSERT INTO $TABLE_NAME (name, roll_number, father_name, dob, gender, address, email, phone, department, program, semester, section) VALUES(:name, :roll_number, :father_name, :dob, :gender, :address, :email, :phone, :department, :program, :semester, :section)";
$pdo_statement = $connect->prepare($SQL);
$pdo_statement->bindparam(':name', $name);
$pdo_statement->bindparam(':roll_number', $roll_number);
$pdo_statement->bindparam(':father_name', $father_name);
$pdo_statement->bindparam(':dob', $dob);
$pdo_statement->bindparam(':gender', $gender);
$pdo_statement->bindparam(':address', $address);
$pdo_statement->bindparam(':email', $email);
$pdo_statement->bindparam(':phone', $phone);
$pdo_statement->bindparam(':department', $department);
$pdo_statement->bindparam(':program', $program);
$pdo_statement->bindparam(':semester', $semester);
$pdo_statement->bindparam(':section', $section);
$result = $pdo_statement->execute();
}
}
else if($count > 0) // IF TABLE EXIST -> INSERT DATA
{
$SQL = "INSERT INTO $TABLE_NAME (name, roll_number, father_name, dob, gender, address, email, phone, department, program, semester, section) VALUES (:name, :roll_number, :father_name, :dob, :gender, :address, :email, :phone, :department, :program, :semester, :section)";
$pdo_statement = $connect->prepare($SQL);
$pdo_statement->bindparam(':name', $name);
$pdo_statement->bindparam(':roll_number', $roll_number);
$pdo_statement->bindparam(':father_name', $father_name);
$pdo_statement->bindparam(':dob', $dob);
$pdo_statement->bindparam(':gender', $gender);
$pdo_statement->bindparam(':address', $address);
$pdo_statement->bindparam(':email', $email);
$pdo_statement->bindparam(':phone', $phone);
$pdo_statement->bindparam(':department', $department);
$pdo_statement->bindparam(':program', $program);
$pdo_statement->bindparam(':semester', $semester);
$pdo_statement->bindparam(':section', $section);
$result = $pdo_statement->execute();
} // ELSE IF ENDS
So i understand you will create the table, if it does not exist and insert data. So call first
$pdo->query("CREATE TABLE $TABLE IF NOT EXISTS;");
It will do nothing, when table exists.
And then insert your data.
$pdo->query("INSERT INTO $TABLE ... ");
No 'if then else' in PHP!
function tableExists($pdo, $table) {
// Try a select statement against the table
// Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
try {
$result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
} catch (Exception $e) {
// We got an exception == table not found
return FALSE;
}
// Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
return $result !== FALSE;
}

Cannot insert data in SQL table when using the same code as previous query

I need to insert two pieces of data into two different tables. It successfully does it with one of the tables but not the second. I have used or die mysqli_error to see if it will tell me the error, but it does not show anything. See the code below:
$sql = "INSERT INTO ticketUsers
(name, emailAddress, password)
SELECT * FROM (SELECT '$name', '$emailAddress', '$dbPassword') AS tmp
WHERE NOT EXISTS (
SELECT name
FROM ticketUsers
WHERE emailAddress = '$emailAddress'
)
LIMIT 1";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering ticket Users";
}
else if(!$result)
{
echo "Cant enter information";
}
$sql = "INSERT INTO tickets
(id, emailAddress, urgency, subject,
description, relevantURL, status)
VALUES ('$id', '$emailAddress', '$username', '$urgency',
'$subject', '$description2', '$relevantURL', 'Open')";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering tickts";
}
else if(!$result)
{
echo "Cant enter information";
}
if (!sql)
{
echo "There has been an error creating your ticket.";
}
In your second query, you try to insert in a table with 7 fields 8 values.
I think you don't want to insert '$username' in the query.

why does php mysql update returns a success but never updated the column?

my basic goal is to update a single row and if it is successful it will insert some data in different table.
here is my query
$upd = mysql_query("UPDATE request_tbl SET status='1' WHERE sender='$user_id' AND reciever='$id'", $con);
if($upd){
$result = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$user_id', '$id')", $con);
$result2 = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$id', '$user_id')", $con);
if($result && $result2){
$jsonresult = $myFunctions->jsonRequest("Sent Request");
}
else{
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
}
note: the scenario is i am updating data to the webserver using android app,
when i try to test the query from using this.
http://----/-----.php?req=accept&user-id=5&id=1
i get a success message and updates, and insert the data in the database. However when i try to send the request from the app it returns a success message and inserts the data, that means that the update was successful but in the database it was never update.
i also tried to change the data type of the column status to int or varchar but still with the same effect, it is weird the insert was excuted but the update was never happened or it was?
EDIT ! ! !
i did try all the recommended solutions like mysql_affected_rows() > 0 and echoing the query but with no luck.. as everyone recommends/insits :) i will try to convert the query into PDO or mysqli thanks for the help everyone.
**EDIT 2 ! ! ! **
i tried to to convert my queries to PDO
here is my code
$upd = $con->prepare("UPDATE request_tbl SET `status`='1' WHERE `sender`='$user_id' AND `reciever`='$id' AND `status`='0'");
try{
$upd->execute();
$result = $con->prepare("INSERT INTO contact_tbl (id, friend_id) VALUES (?, ?)");
$result->bindParam(1, $user_id);
$result->bindParam(2, $id);
$result2 = $con->prepare("INSERT INTO contact_tbl (id, friend_id) VALUES (?, ?)");
$result2->bindParam(1, $id);
$result2->bindParam(2, $user_id);
try{
$result->execute();
$result2->execute();
$jsonresult = $myFunctions->jsonRequest("Sent Request");
}
catch(PDOException $e){
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
}
catch(PDOException $e){
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
echo $jsonresult;
but i recieve the same result, whenever i try it using the url method the update and insert are successful with the correct value, but when i do it with the app the update and insert returns successful and the insert have the correct value but the update did not change the column im changing..
use mysql_affected_rows() to check how many rows were affected. Try this,
if(mysql_affected_rows()){
// your stuff here.
}
try this folk, use mysql_num_rows(). mysql_affected_rows() give you a nums of rows afected by the last query executed. and you know how manny rows are afected. Hope this can help you
$upd = mysql_query("UPDATE request_tbl SET status='1' WHERE sender='$user_id' AND reciever='$id'", $con);
$NumsRowsAfected = mysql_affected_rows();
if(mysql_affected_rows() > 0){
$result = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$user_id', '$id')", $con);
$result2 = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$id', '$user_id')", $con);
if($result && $result2){
$jsonresult = $myFunctions->jsonRequest("Sent Request");
}
else{
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
}
Make sure that values of $user_id and $id getting on the current page you are in.
Hopefully, you passed the user id variable as user-id and retrieved as $_GET['user-id'].
If its perfect then, echo both queries and run the printed query on phpmyadmin manually. That will through the erroe
echo $result = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$user_id', '$id')", $con);
echo $result2 = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$id', '$user_id')", $con);
more over mysql_query has been deprecated. Those functions will be no more exist. Try PDO or MySQLi

php - Insert doesn't enter values to form

Hi guys i dont know what im doing wrong but my tables are correct, php error is on and it doesnt insert
I can get both first name and email echoed
<?php
if (isset($_POST['subs'])) {
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
$name=html_escape($_POST['name']);
$email=html_escape($_POST['email']);
if (empty($name) || empty($email)) {echo"<div class='alert alert-danger'>Please enter both name and email address</div>";}
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo"<div class='alert alert-danger'>Invalid email address, please enter a correct email address!</div>";
}
else {
echo "INSERT into subs (first_name, email) VALUES ('$name','$email')";
$insert=mysql_query("INSERT into subs (first_name, email) VALUES ('$name','$email')");
if ($insert) {echo"<div class='alert alert-success'>Thank you for subscribing with us</div>";}
}
}}
?>
first of all, are you connected to mysql before running your query?
$conn=mysql_connect('localhost', 'your_db_username', 'your_db_password');
if(!$conn){
die('Cannot connect to mysql');
}
mysql_select_db('your_db_name');
Then, when you're sure you're connected to the db and your query is still not working, add or die(mysql_error()) after your query like this, this will help you know what's going wrong with your insert:
$insert=mysql_query("INSERT into subs (first_name, email)
VALUES ('$name','$email')")
or die(mysql_error());
As a general point, using the PDO class is preferred, and may give you more information about what the problem is.
e.g.
$pdo = new \PDO('mysql:host=localhost;dbname=<database_name>', '<database_username>', '<database_password>');
$sql = "INSERT into subs (first_name, email) VALUES (:name,:email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$result = $stmt->execute();
This gives a lot of benefits. Take my word for it, or give "benefits of PDO" a quick Google.
$query = "INSERT INTO subs (first_name, email) VALUES ('" . $name . "','" . $email . "') ";
$insert = mysql_query($query);

Categories