PHP MySQL inserting information from one form into multiple tables - php

So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}

First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}

Related

How to change from simple mysqli query to prepared statement?

I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}

Unable to post to a database MySQL

I am attempting to post a column into my database here as a test and I am unable to do so. I've used the code below and it doesn't seem to be posting. Unless I am missing a trick with PHPmyAdmin I cannot seem to get it working. Any chance anyone could help? Thanks in advance!
<?php
$link = mysqli_connect("XXXX", "XXXX",
"XXXX", "XXXX");
if (mysqli_connect_error ()) {
die("The connection has failed");
}
$query = "INSERT INTO `users` (`email`, `password`)
VALUES('owen#owen.com', 'hfudhf8ahdfufh')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo"Your Email is ".$row["email"];
echo" and your Password is ".$row["password"];
}
?>
The problem is that you're only fetching one row of results. Unless the table was empty before you ran the script, there's no reason to expect that row to be the one that you just added.
If the table has an auto-increment ID field, you can fetch that row:
$query = "SELECT * FROM users WHERE id = LAST_INSERT_ID()";

How do I echo name, price and id from a form just submitted?

I have an issue with MySQLi and PHP.
I created a form, and once I type the desired values in and hit submit, the values are right away sent to the database. Nothing wrong with this.
What I want to happen is that: after hitting the submit button, PHP shall echo the result of the just-submitted entry. That is to say:
`INSERT INTO table VALUES (x, x, y) -> SELECT x, x, y FROM table ORDER BY id DESC LIMIT 1`
I have tried many methods to do this, but all of them either echo the previous entry (the one before the one just submitted) or plainly don't work.
I have tried mysqli_insert_id($conn) but this returns nothing.
This is where my code rests at at the moment:
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$nome = $_POST['nome'];
$preco = $_POST['preco'];
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$result = mysqli_insert_id($conn);
var_dump ($result);
if (mysqli_query($conn, $query)){
echo '<br>'."Succeeded!";
} else {
echo '<br>'."ERROR!" .'<br>'. $query ."<br>". mysqli_error($conn) .'<br><br>'. '<span style="color: #FF0000;">You have to fill all the fields.</span>';
}
mysqli_close($conn);
to note, if of any help, var_dump outputs int(0) at the moment.
Thanks in advance. I've been struggling like mad with this.
You can't get mysqli_insert_id without executing the query. Better use prepare statement to prevent from sql injection
$stmt = $conn->prepare("INSERT INTO produtos(nome, preco) VALUES (?,?)");
$stmt->bind_param('ss', $nome, $preco);
$stmt->execute();// execute query
$conn->insert_id;// get last insert id
Please see that you haven't even executed your query. On a side note, you should be aware of SQL injections and follow the below pattern:
$nome = mysqli_real_escape_string($conn, $_POST['nome']);
$preco = mysqli_real_escape_string($conn, $_POST['preco']);
$sql = "INSERT INTO produtos (nome, preco) VALUES ('".$nome."', '".$preco."')";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result = mysqli_insert_id($conn);
echo $result; // Check your result.
Use this:
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$res=mysqli_query($conn,$query);
$result = mysqli_insert_id($conn);
var_dump ($result);`

MySqli not working correctly

My goal is to recieve 2 strings, an IP and UUID, and look in the database. If the UUID is already there, it adds the IP onto a list of IPs in the database. If not, it makes a new row in the database with that UUID and IP. Purpose is tracking user activity (Nothing malicious)
Code:
<?php
$cip = $_POST['ipaddr'];
$cid = $_POST['id'];
$conn = mysqli_connect('localhost', '*****', '*****', '*****');
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
if(mysqli_num_rows($query) > 0){
$sql = "SELECT asid, ips FROM sls WHERE asid=$cid";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$cipdata = $row["ips"];
}
$sql = "UPDATE sls SET ips='$cipdata , $cip' WHERE id=2";
mysqli_query($conn, $sql);
} else {
$sql = "INSERT INTO sls (asid, ips) VALUES ('$cid', '$cip')";
mysqli_query($conn, $sql);
}
?>
Right now, it just adds a new row for every IP, regardless of UUID.
What did I do wrong?
-- Edit: Fixed typo, now it just adds the first IP, but after that does not add any more to the row.
Perhaps there is a small typo on this line:
$query = mysqli_query($con, "SELECT * FROM sls WHERE asid='".$cid."'");
Did you mean $conn, not $con? As in:
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
Your connection param is $conn so just used this in every query command. some where you are using $con and somewhere $conn.
Check your code.

Multiple Results being uploaded to table

I've been struggling with trying to add the same variable into two of the tables I have on my database and so have decided to work around it and use two separate insert statements instead
if ($cuisinetype !='empty'){
$query="SELECT cuisine_type FROM `Nation` WHERE cuisine_type='$cuisine'";
$result=mysqli_query($db_server, $query) ;
if ($row = mysqli_fetch_array($result)){
$message = "Sorry we already have that one!";
}else{
$query = "INSERT INTO`Nation`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) ;
$query2 = "INSERT INTO`recipename`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) ;
}
}
This is how my sql statement looks right now, but now it's putting two variables into my Nation table and still nothing into the recipename table
Still relatively new to all things PHP/MySQL and considering beforehand it was working am very confused.
try this under your second insert:
mysqli_query($db_server, $query2) or ... Replace the $query with $query2

Categories