I have two table Billing_month and registration in mysql. i want to insert into Billing_month and at the same time i want to update a row (Arrears) in registration table. how can i do this.
PHP Code is:
<?php
//create connection
include("database/db.php");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Insert Data
#$month=$_POST['Bill_month'];
#$issuedate=$_POST['Bill_issue_date'];
#$duedate=$_POST['Bill_due_date'];
#$surcharge =$_POST['Surcharge'];
$sql = "INSERT INTO billing_month (Bill_month,Bill_issue_date,Bill_due_date,Surcharge) values('$month','$issuedate','$duedate','$surcharge')";
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);
?>
Need your help?
I would only run the query update if the insert was successful.
<?php
//create connection
include("database/db.php");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Insert Data
#$month=$_POST['Bill_month'];
#$issuedate=$_POST['Bill_issue_date'];
#$duedate=$_POST['Bill_due_date'];
#$surcharge =$_POST['Surcharge'];
$sql = "INSERT INTO billing_month (Bill_month,Bill_issue_date,Bill_due_date,Surcharge)
values('$month','$issuedate','$duedate','$surcharge')";
if(mysqli_query($link, $sql)){
$res = "Records added successfully.";
// Update Registration Arrears query
$sql_upadte = "Update registration ...."
if(mysqli_query($link, $sql_update)){
$res .= "<br>Registration record updated successfully.";
}else{
$res .= "<br>ERROR: Could not able to execute.<br>".$sql_update."<br>".mysqli_error($link);
}
echo($res);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Use two queries to insert and to update, then execute them
$sql = "INSERT INTO billing_month (Bill_month,Bill_issue_date,Bill_due_date,Surcharge)
values('$month','$issuedate','$duedate','$surcharge')";
$sqlUpdate = "Place your update query here";
$insert = mysqli_query($sql);
$update = mysqli_query($sqlUpdate);
After insert into your billing table get last inserted id
$id = mysql_insert_id();
Then update your registration table.
$query = "UPDATE registration SET .... WHERE billing_id = $id; ";
mysql_query($query);
This is a simple multi query, you can look at php - multi_query here.
<?php
$query = "INSERT INTO billing (...) VALUES (....) ; ";
$query .= "UPDATE billing SET .... ; ";
if(!mysqli_multi_query($link,$query)){
...
}
Otherwise you can still do just do two single queries and execute them one after the other
Related
I'm trying to build a database for a bookstore with 3 tables: Book, Volume and Publication. I'm using mysqli() and the code neither works nor echoes any errors.
<?php
//connect to db
$conn = new mysqli("localhost", "root", "", "ershadbookstore");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
#new recoed: if the new record is inserted into book successfully, another new record is inserted into volume table. the same goes for volume and phblication table. at the end the total number of this volumn is editted in the rows with the same isbn.
$sql = "INSERT INTO Book (name, vnum, writer, translator, publisher, genre, format)
VALUES ('test', 'test', 'test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$last_bid = $conn->insert_id;
$sql = "INSERT INTO Volume (isbn, bid, vnum, note, image)
VALUES ('test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO Publication (isbn, pubnum, pyear, circulation, fpyear, pnum, price, num)
VALUES ('test', 'test', 'test', 'test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$sql= "SELECT SUM(num) FROM Publication
WHERE (isbn='test')";
if ($conn->query($sql) === TRUE) {
$totalNum=$conn->query($sql);
$sql1= "UPDATE Volume
SET (tnum = test)
WHERE (isbn= test)";
if ($conn->query($sql1) === TRUE)
{
echo "true";
}
else
{
return "Error publication table: " . $sql1 . "<br>" . $conn->error;
}
}
}
else{
return "Error publication table: " . $sql . "<br>" . $conn->error;
}
}
else {
return "Error for volume table: " . $sql . "<br>" . $conn->error;
}
}
else {
return "Error for book table: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The problem is that you are checking with === TRUE.
As PHP Manual says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
While your error checking would work for INSERT or UPDATE queries the SELECT query will not return true. In fact checking like this for boolean values is completely unnecessary.
Remove the check for === TRUE and your code should work fine.
$sql= "SELECT SUM(num) FROM Publication
WHERE isbn='test'";
if ($conn->query($sql)) { // removed === TRUE
$sql1= "UPDATE Volume
SET tnum = 'test'
WHERE isbn= 'test'";
if ($conn->query($sql1))
{
echo "true";
}
else
{
return "Error publication table: " . $sql1 . "<br>" . $conn->error;
}
}
If you enable mysqli error reporting, you don't need any if statements, which will make your code much simpler:
$sql = "SELECT SUM(num) FROM Publication
WHERE isbn='test'";
$conn->query($sql);
$sql1 = "UPDATE Volume
SET tnum = 'test'
WHERE isbn= 'test'";
$conn->query($sql1);
echo "true";
In addition, your values in the last update queries are missing quotes.
SET (tnum = 'test')
WHERE (isbn= 'test')";
Also there is no need to execute your SELECT query twice to get the values. You should refactor your code so that the second query ($totalNum=$conn->query($sql);) is not needed.
Also remove the triple equals === you are not comparing so you don not need a comparison operator so instead use !== FALSE
Example
if ($conn->query($sql) !== FALSE)
so this is saying if its not FALSE, than its TRUE so it will continue to run.
goodness.. it's been a quite a headache for me.
I'm trying to get variable SQL1, SQL2 and SQL3 to update different mysql tables.. but how on earth will SQL2 and SQL3's "product_id" fields, correlate with SQL1?
See 'id' in the insert sections in SQL2 and SQL3.. i'm not sure how to replace and grab this generated data into this sections without making more ugly code.
Also, if any of you have any idea how to make this easier, please help a fellow out here.. this looks pretty dirty to me.. surely there are better ways :(
// DB Settings
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Load data from XML file
$xml = simplexml_load_file("Datafeed.xml");
// Capture XML Data
foreach($xml->children() as $product) {
// Change stock wording
$stock = $product->stock;
if ($stock == 'yes') {
$stock = 'on';
} else {
$stock = 'off'; }
// Convert XML data and insert into MYSQL
$sql = "INSERT INTO testshop_products (product_id, product_name, product_type, product_price, product_status) VALUES ("echo $product->code;", "echo $product->cat;", "echo $product->price;","echo $stock;")";
$sql2 = "INSERT INTO testshop_product_details (product_id, product_color, product_image, details_status) VALUES ('id', "Generating...", "echo $product->img;","echo $stock;")";
$sql3 = "INSERT INTO testshop_spesifications (product_id, specs_meta, specs_details, specs_slug, specs_status) VALUES ('id', General, "echo $product->img;", general, "echo $stock;")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
write store procedure and inset all records and all table it will find.
store procedure like this
CREATE PROCEDURE `addJobApplicant`(IN XMLINPUT
text, OUT vresult VARCHAR(100))
BEGIN
DECLARE iCounter INT DEFAULT 1;
DECLARE maxCount INT;
SET vcompID=ExtractValue(XMLINPUT, '/ROOT/HEADER/COMPANYID[$iCounter]');
SET vjpID=ExtractValue(XMLINPUT, '/ROOT/HEADER/JOBID[$iCounter]');
insert command here
SET vresult = 'Successfully Inserted';
end
I figured out how to run Arp-scan and show the results on the page. Now I need to insert the information into a Mysql DB. I know how to insert a single record, but I struggle with how to get many records into the db. Can't seem to wrap my head around it. Here's my code
<?php
$link = mysqli_connect("localhost", "user", "password", "mydb");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
error_reporting(E_ALL);
ini_set('display_errors', '1');
$output = shell_exec("sudo arp-scan --interface=eth0 --localnet --numeric -- quiet| grep -e 80:82:87");
foreach (explode("\n", $output) as $host)
{
list($ip, $mac) = array_pad(explode("\t", $host),2,null);
echo "$ip $mac<br>";
}
// attempt insert query execution
$sql = "INSERT INTO phones (ipadd, mac) VALUES ('$ip', '$mac')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Any help is greatly appreciated
<?php
$values = array();
foreach (explode("\n", $output) as $host)
{
list($ip, $mac) = array_pad(explode("\t", $host),2,null);
$values[] = '("'.$ip.'", "'.$mac.'")';
}
// attempt insert query execution
$sql = "INSERT INTO phones (ipadd, mac) VALUES ".implode(',', $values);
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It will create an array of strings in following format:
("IP", "MAC")
and connect them later using a comma
("IP", "MAC"),("IP2", "MAC2")
and add into the query
this is my code at insertion its working but at the time of comparison its showing parse syntax error
// attempt insert query execution
$sql = "INSERT INTO availer (source_name, dstntn_name, sou_date, flight_no, sou_weight, contact_name, contact_no) VALUES ('$source_name', '$dstntn_name', '$sou_date', '$flight_no', '$sou_weight', '$contact_name', '$contact_no')";
if(mysqli_query($link, $sql)){
$sql ="SELECT availer.id, availer.source_name,availer.dstntnn_name,availer.sou_date,availer.sou_weight FROM availer availer
WHERE EXISTS (SELECT * FROM provider provider
WHERE provider.source_name = availer.source_name AND provider.dstntn_name = availer.dstntn_name AND provider.sou_date = availer.sou_date AND provider.flight_no = availer.flight_no");
print $query;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You missplaced the " mark. Your code should be like this.
$sql = "INSERT INTO availer (source_name, dstntn_name, sou_date, flight_no, sou_weight, contact_name, contact_no) VALUES ('$source_name', '$dstntn_name', '$sou_date', '$flight_no', '$sou_weight', '$contact_name', '$contact_no')";
if(mysqli_query($link, $sql)){
$sql ="SELECT availer.id, availer.source_name,availer.dstntnn_name,availer.sou_date,availer.sou_weight FROM availer availer
WHERE EXISTS (SELECT * FROM provider provider
WHERE provider.source_name = availer.source_name AND provider.dstntn_name = availer.dstntn_name AND provider.sou_date = availer.sou_date AND provider.flight_no = availer.flight_no)";
print $query;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "prog_db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$source_name = mysqli_real_escape_string($link, (isset($_POST['source'])));
$dstntn_name = mysqli_real_escape_string($link,(isset($_POST['dstntn'])));
$sou_date = mysqli_real_escape_string($link,(isset($_POST['date'])));
$flight_no = mysqli_real_escape_string($link,(isset($_POST['flightno'])));
$sou_weight = mysqli_real_escape_string($link,(isset($_POST['weight'])));
$contact_name = mysqli_real_escape_string($link,(isset($_POST['name'])));
$contact_no = mysqli_real_escape_string($link,(isset($_POST['contact'])));
// attempt insert query execution
$sql = "INSERT INTO availer (source_name, dstntn_name, sou_date, flight_no, sou_weight, contact_name, contact_no) VALUES ('$source_name', '$dstntn_name', '$sou_date', '$flight_no', '$sou_weight', '$contact_name', '$contact_no')";
if(mysqli_query($link, $sql)){ $sql ="SELECT availer.id, availer.source_name,availer.dstntnn_name,availer.sou_date,availer.sou_weight FROM availer availer
WHERE EXISTS (SELECT * FROM provider provider
WHERE provider.source_name = availer.source_name AND provider.dstntn_name = availer.dstntn_name AND provider.sou_date = availer.sou_date AND provider.flight_no = availer.flight_no)";
$result = mysql_query($sql,$link);
while($row = mysql_fetch_array($result)) {
echo $row['SOURCE_name'];
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
but i am not able to fatch the result on the webpage .
You should write this
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if (isset ($_POST['source'], $_POST['dstntn'], $_POST['date'], $_POST['flightno'],$_POST['weight'],$_POST['name'], $_POST['contact'])){
$source_name = mysqli_real_escape_string($link,$_POST['source']);
$dstntn_name = mysqli_real_escape_string($link,$_POST['dstntn']);
$sou_date = mysqli_real_escape_string($link,$_POST['date']);
$flight_no = mysqli_real_escape_string($link,$_POST['flightno']);
$sou_weight = mysqli_real_escape_string($link,$_POST['weight']);
$contact_name = mysqli_real_escape_string($link,$_POST['name']);
$contact_no = mysqli_real_escape_string($link,$_POST['contact']);
// attempt insert query execution
$sql = "INSERT INTO availer (source_name, dstntn_name, sou_date, flight_no, sou_weight, contact_name, contact_no) VALUES ('$source_name', '$dstntn_name', '$sou_date', '$flight_no', '$sou_weight', '$contact_name', '$contact_no')";
if(mysqli_query($link, $sql)){ $sql ="SELECT availer.id, availer.source_name,availer.dstntnn_name,availer.sou_date,availer.sou_weight FROM availer availer
WHERE EXISTS (SELECT * FROM provider provider
WHERE provider.source_name = availer.source_name AND provider.dstntn_name = availer.dstntn_name AND provider.sou_date = availer.sou_date AND provider.flight_no = availer.flight_no)";
$result = mysql_query($sql,$link);
while($row = mysql_fetch_array($result)) {
echo $row['SOURCE_name'];
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
I have check all the parameters and they are having the correct data in them but my query is not updating data in table.
Here is the code :
public function updateRooms($capacity,$rent,$h_id,$t_rooms){
$conn=DB::connect();
for($i=1; $i<=$t_rooms; $i++){
$room_no=$i;
$sql= "UPDATE room SET ro_capacity='{$capacity[$i]}', ro_rent='{$rent[$i]}', ro_room_no='$room_no' WHERE h_id=".$h_id;
if($conn->query($sql) === TRUE){
$last_id = $conn->insert_id;
echo "New record created successfully.". $last_id;
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
}
There is no point in getting insert id from UPDATE query. It won't get you anything useful.
Besides, you should be using prepared statements.
public function updateRooms($capacity,$rent,$h_id,$t_rooms){
$conn=DB::connect();
$sql= "UPDATE room SET ro_capacity=?, ro_rent=?, ro_room_no=? WHERE h_id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iiii",$ro_capacity,$ro_rent,$i,$h_id)
for($i=1; $i<=$t_rooms; $i++){
$ro_capacity = $capacity[$i];
$ro_rent = $rent[$i];
$stmt->execute();
echo "The record updated successfully";
}
}
As you can see, mysqli is almost unusable with prepared statements. This is why you have to use PDO:
$sql= "UPDATE room SET ro_capacity=?, ro_rent=?, ro_room_no=? WHERE h_id=?";
$stmt = $conn->prepare($sql);
for($i=1; $i<=$t_rooms; $i++){
$stmt->execute([$capacity[$i],$rent[$i],$i,$h_id]);
echo "The record updated successfully";
}
}