How to have 2 insert queries on a single php file - php

I want to insert data from 2 different tables in a single php file. Only the first insert query will be executed. please help, thank you!
<?php
//session_start();
include('config.php');
//$_SESSION['ID'] = $ID
//Data from guestAdd.php
$aID = $_POST['id'];
$afrom = $_POST['from'];
$ato = $_POST['to'];
$aleaveType = $_POST['leaveType'];
$selectRemarkSql = mysqli_query($conn, "SELECT remarkName FROM remarks WHERE remarkID = '$aleaveType';");
while($row = $selectRemarkSql ->fetch_assoc()) {
$leaveType = $row["remarkName"];
}
$addAbsentSql = mysqli_query($conn, "INSERT INTO absent(afrom, ato, aleaveType, empID) VALUES('$afrom', '$ato', '$leaveType', '$aID');");
$leaveLogUpdateSql = mysqli_query($conn, "INSERT INTO attendance(empID, HoursWorked, remarks, holiday) VALUES('$aID', 00:00:00, '$aleaveType', 'None');")
header("Refresh: viewAllEmployees.php");
?>

Check for errors between the queries. Make sure to stop the header refresh so that the error message is displayed.
$addAbsentSql = mysqli_query($conn, "INSERT INTO absent(afrom, ato, aleaveType, empID) VALUES('$afrom', '$ato', '$leaveType', '$aID');");
echo myslqi_error($conn);
$leaveLogUpdateSql = mysqli_query($conn, "INSERT INTO attendance(empID, HoursWorked, remarks, holiday) VALUES('$aID', 00:00:00, '$aleaveType', 'None');")
//header("Refresh: viewAllEmployees.php");

Related

inserting in mysqli is not working

I am trying to get data from one table and inserting it in another table.
But the problem is that it is not inserting.
Here is my code
$query = "SELECT id,pname,medicin FROM logpn WHERE id = '$login_session'";
$result = mysqli_query($dbhandle,$query);
while( $row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$id = $row['id'];
$pname = $row['pname'];
$med = $row['medicin'];}
if (isset($_POST['button1'])) {
mysqli_query($dbhandle,"INSERT INTO medicin_refill (id, pname, medicin) VALUES ('$id', '$pname', '$med')") or die(mysqli_error($dbhandle));
Can anyone tell me what is wrong??
Maybe try VALUES ($id,[...] instead of VALUES ('$id',[...] because the $id shouldn't be a string.

Need help inserting info into the database and returning it back

In my code I had three radio buttons that user click to choose the color of each title, text and button that is in hex value. And it is sending info properly, but when the code running that puts everything into the database it's sending user to the to the home page saying that color had been changed, but it did not.
Here's my php code:
session_start();
if (isset($_SESSION['username'])) {
include 'databaseconnection.php';
$username = $_SESSION['username'];
$titlecolor = $_POST['titlecolor'];
$textcolor= $_POST['textcolor'];
$buttoncolor = $_POST['buttoncolor'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: index.php?wronghappened");
exit();
}
else {
if ($row = mysqli_fetch_assoc($result)) {
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
$_SESSION['id'] = $row['id'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
$_SESSION['text'] = $row['text'];
$_SESSION['title'] = $row['title'];
$_SESSION['button'] = $row['button'];
header("Location: home.php?color_changed");
exit();
}
}
}
else {
header("Location: index.php?not_in");
exit();
}
You are not using the update query. Excute your update query so it will update the db.
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
mysql_query($update);
Instead of
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
The variable textcolor is being sent to the server as a string, not a variable because you have wrapped it in qoutes. You should only wrap qoutes around strings to be sent as values. Use this instead:
$update = "UPDATE students (titlecolor, textcolor, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
Then to execute this code, run
mysql_query($con, $update);
Replace your query with this:
$updatequery = "UPDATE students set titlecolor='$titlecolor', textcolor='$textcolor', buttoncolor='$buttoncolor' WHERE uname='$uname'";
Now Check that is query successfully executed ?
if (mysqli_query($con, $updatequery))
{
echo "successfully execute.....";
//do something here
}
else
{
echo "Sorry query can't executed!";
echo "My Query ".$updatequery;
}
If query not execute then you will see your query after "My Query ", So copy that query and execute it in your mysql then you will find main error.
Try this
$update = "UPDATE students SET titlecolor='$titlecolor', textcolor='$textcolor', buttoncolor='$buttoncolor' WHERE uname='$uname'";
$updateResult = mysqli_query($con, $update);
instead of
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
If your will not execute your query using mysqli_query then it won't show any effect.
Also I will like to suggest you to use PDO in the future instead of mysqli. For this reasons.
Happy Coding :)

PHP header not working

I have a web page that will get the data using POST method from the other page and then store the data to the database. After it's done, I want it to go back to the page where the data comes from. I used header(). But it didn't work.
Here's my code:
<?php
$date = $_POST['date'];
$spent = $_POST['spent'];
$description = $_POST['description'];
$dbc = mysqli_connect('oniddb.cws.oregonstate.edu', 'chentao-db', 'BUU3UuwwGfwt7hxV', 'chentao-db')
or die(mysql_error());
$query = "SELECT Total FROM Expense E ORDER BY E.Index DESC LIMIT 1";
//get the total
$result = mysqli_query($dbc, $query) or die(mysql_error());
$total = mysqli_fetch_array($result, MYSQL_ASSOC);
$total = $total['Total'] + $spent;
$query = "INSERT INTO Expense (Date, Spent, Total, Description) VALUES ('$date', '$spent', '$total', '$description')";
$result = mysqli_query($dbc, $query) or die(mysql_error());
mysql_close($dbc);
header("Location: fetchData.php");
?>
What's wrong with it? Thank you.
I guess it would work something like this
header("Location: http://".$_SERVER['HTTP_HOST']."/fetchData.php");
try to place
ob_start();
at top of your file..
Or you can try
header('Location: '.$_SERVER['HTTP_REFRER']);
die;
don't forget to place die at last.
If your first query does not return any result, then the execution fails at this line:
$total = $total['Total'] + $spent;
Check if the first query has any results like this:
if(isset($total['Total'])){
$total = $total['Total'] + $spent;
}
else {
$total = $spent;
}

Is it possible to concatenate this INSERT query in and out of a if statment?

I'm having a few issues with this silly query, was wondering is it possible to concatenate the following INSERT query inside the IF statement and outside it as well to complete the rest of the query. So I want the $orderid to be insert within the if statement and the rest of the last 3 variables outside the IF
if(isset($_POST['Submit'])){
$orderid=mysql_insert_id();
$sql = mysql_query("SELECT * FROM course WHERE serial='$serial'") or die(mysql_error());
$fetch = mysql_fetch_assoc($sql);
$serial = $fetch['serial'];
$price = $fetch['price'];
mysql_query("INSERT into course_order_detail values ('$orderid','$serial','1','$price')") or die(mysql_error());
}
Oh and $orderid is from the previous insert query written in my code.
Try Like this
if(isset($_POST['Submit'])){
$orderid=mysql_insert_id();
$sql = mysql_query("SELECT * FROM course WHERE serial='$serial'") or die(mysql_error());
$fetch = mysql_fetch_assoc($sql);
$serial = $fetch['serial'];
$price = $fetch['price'];
$in = mysql_query("INSERT into course_order_detail values ('$orderid')") or die(mysql_error());
$new_id = mysql_insert_id();
}
$up = mysql_query("UPDATE course_order_detail SET serial='$serial',quantity='1',price='$price' WHERE orderid = ".$new_id);
You can use a nested insert with select
INSERT `into course_order_detail` SELECT '$orderid', serial, '1', price FROM course WHERE serial='$serial'
BTW sanitize your queries

inserting values from a loop

$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2="INSERT INTO registered ( ServiceID, IDno, Stype)VALUES('$RecCode','$IDno','$Stype')";
}
this is my code. its working but it only insert one data into the database. How can make it away to insert all the possible data from the loop. Can anyone help me?
You’re probably executing the query after the loop so only the last record is being inserted.
Try to execute the insertion query at the end of the loop:
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
mysql_query($sql2);
}
Or you first collect all data and then do one query to insert all records:
$values = array();
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$values[] = "('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
}
if (!empty($values)) {
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ".implode(',', $values);
mysql_query($sql2);
}
But don’t forget to prepare the values for the query (see mysql_real_escape_string function).
If you are not planing to do anything with the fetched data, you could use INSERT .. SELECT .. statement.
Example:
INSERT INTO registered (ServiceID, IDno, Stype)
SELECT field1, field2, field3
FROM class
WHERE SubjID='$SubjName' and SecID='$SecName'"
And like written before me, escape your variables...
Note: make sure you're escaping your variables with mysql_real_escape_string.
$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ";
$addComma = false;
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2 .= ($addComma ? ", " : "") . "('$RecCode','$IDno','$Stype')";
$addComma = true;
}
Change this line:
$sql2="INSERT INTO registered..."
to this:
$sql2 .= "INSERT INTO registered..."
inside the loop. You are accidentally overwriting the insert statement each time. If you use .= you will append the next statement to the previous one, creating a batch of insert scripts, one for each record.

Categories