Facing problem in insert value into multiple row - php

I am writing a PHP script where it takes data from a database table where there are more than ten rows. After taking all the rows' input from the database it adds with a variable. After that those sum value is inserted to all the rows of another database. My code is working fine in fetching all the rows' data from the database and add a number to that value. But it does not insert new data into another database. I am not getting any error messages. My code:
<?php
include("dbconnect.php");
$query = "SELECT * FROM down_value";
$down_value_db = $conn->query($query);
/*Time Deference Variable*/
$td1=1;
$date = date("Y-m-d");
while ($row = mysqli_fetch_assoc($down_value_db)) {
/*Value from db*/
$s_data1=$row['TGI_R'];
/* Simulated Data*/
$e_data1=$s_data1+$td1;
//Insert Data into database
$insert = $conn->query("INSERT into down_simulation (TGI_R,date) VALUES ('$e_data1', '$date')");
if($insert){
echo "$e_data1 <br/>Successfully data Recorded <br/>";
}else{
echo "Error";
}
}
?>

you must add your select values to array and then with for loop insert this values to another table.
$query = mysqli_query($conn,"select tgi_r from down_value");
$tgi_r_array = array();
$date_time = date("Y-m-d H:i:s");
while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
$tgi_r_array[] = $row['tgi_r']+1;
}
for ($i = 0; $i < count($tgi_r_array); $i++){
$insert = mysqli_query($conn, "insert into down_simulation(tgi_r,date) values ('" . $tgi_r_array[$i] . "', '" . $date_time . "')");
}
print_r($tgi_r_array);

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.

MySQL Update Database Where Post Values is in Array

I have a site where users can input multiple values in the text fields, so I created an array for the post values and have successfully inserted the values of the array into the database.
I have a problem updating these values that I have stored in the database. I tried this but it's not working.
<?php
if (!empty($_POST['sub_cat'])) {
$cat_id = $_GET['c_id'];
$subcat_title_array = $_POST['sub_cat'];
for ($i = 0; $i < count($subcat_title_array); $i++) {
$subcat_title = mysqli_real_escape_string($connection, $subcat_title_array[$i]);
$query = "UPDATE sub_categories SET subcat_title = '{$subcat_title}' WHERE subcat_id = $cat_id";
$update_sub_category = mysqli_query($connection, $query);
if (!$update_sub_category) {
die("Query Failed " . mysqli_error($connection));
}
}
}
?>
Is there anything am doing wrong?
Any help will be appreciated.

Inserting data in two columns on same row simultaneously

I have a table in a mysql database with only two columns and I want to insert data in both columns on the same row simultaneously using php. I have tried the following php script but it inserts data in the one row then the other as follows:
1-NULL
NULL-4
I want both 1 and 4 to be on the same row. Here's my php script:
<?php
$first_value = 1;
$second_value = 2;
$qry = "INSERT INTO my_table (first_value) VALUES ('$first_value')";
$qry .= "INSERT INTO my_table (second_value) VALUES ('$second_value')";
if($conn->multi_query($qry) === TRUE){
echo "success";
}
else {
echo "Error: " . $qry . "<br>" . $conn->error;
}
$conn->close();
?>
It inserts successfully. But I want the insert to be on the same row. Any help will be greatly appreciated.
just use a proper insert
$qry = "INSERT INTO my_table (first_value, second_value)
VALUES ('$first_value', '$second_value')";

How to combine MULTIPLE INSERTS into database?

My submission form works fine but there are 3 insert queries in the code.
Let me explain why.
Insert Query 1 allows the selected value of the dropdown menu on the form to be inserted into the database table.
Insert Query 2 allows the values inside of a text area box to be inserted into individual separate rows
Insert Query 3 allows all other data to be inserted.
The HTML looks like this (it is wrapped inside of a code but I'll just include a few snippets)...
The dropdown menu:
<select name="Name" id="">
<?php
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['Name']; ?>"><?php echo $row['Name']; ?> </option>
<?php
} ?>
</select>
Yes, I know....it's not using mysqli or PDO at the moment....I've been told that numerous times....
The textarea which will hold multiple lines of values:
<textarea rows="10" cols="35" name="BachelorsDegrees"> </textarea>
Everything else on the form is just <input>. Pretty simple.
The PHP...
Inserting the text area values into the database:
//Writes the information to the database
$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $BachelorsDegrees) {
mysql_query("INSERT INTO Colleges (BachelorsDegrees) VALUES ('$BachelorsDegrees')") or die(mysql_error()) ;
}
Inserting the selected drop down menu value:
//if (isset ($_POST['upload']))
//{
$Name=trim($_POST['Name']);
$ins=mysql_query("INSERT INTO Colleges (Name) VALUES ('$Name')") or die(mysql_error()) ;
if($ins)
{
echo "<br>".$Name."inserted";
}
else
{
echo mysql_error();
}
//}
And inserting everything else:
mysql_query("INSERT INTO Colleges (schoollogo,Motto,Description,Type,ReligiousAffiliation,OtherPartnerships,GenderAdmission,TermType,EntranceExam,EntranceExamDate,TotalEnrolled,collegewebsite,ContactInfo,CampusLocations,Certifications,Diplomas,AssociateDegrees,MastersDegrees,DoctorateDegrees,SpecialDegreePrograms,Accreditation,CostofTuitionLocal,CostofTuitionForeign,Housing,AcceptanceRate,CoE,CoD) VALUES ('$schoollogo', '$Motto', '$Description', '$Type', '$ReligiousAffiliation', '$OtherPartnerships', '$GenderAdmission', '$TermType', '$EntranceExam', '$EntranceExamDate', '$TotalEnrolled', '$collegewebsite', '$ContactInfo', '$CampusLocations', '$Certifications', '$Diplomas', '$AssociateDegrees', '$MastersDegrees', '$DoctorateDegrees','$SpecialDegreePrograms','$Accreditation','$CostofTuitionLocal','$CostofTuitionForeign','$Housing','$AcceptanceRate','$CoE','$CoD')") or die(mysql_error()) ;
When inserted into the database, multiple rows of data are shown.
1 row = College Name (from the drop down menu)
2nd row = the degrees from the text area
3rd row = all other data
How do I combine all insert queries into one query so that I only have 1 row?
Generally you build a single query.
Take each of the values and add them to the query (probably as parameters).
However you appear to have a single table, rather than multiple tables. You would expect to have a table of colleges, and then another table that has a row for each course each college does.
An alternative would be for your first query to return the unique id of the inserted row, and then all your other inserts also insert this id with an ON DUPLICATE KEY UPDATE clause. But this would be messy and slow
EDIT.
Example of a single query. Note that I have just used the deprecated mysql_* functions as that is what you are using, but you should switch to either the mysqli_* functions or to PDO . Either way escaping the data or using parameterised queries is VERY important.
This inserts one record for the college, then uses mysql_insert_id() to get the id field of the inserted field (assuming you have one). This id is then used to insert each of the courses to another table listing the courses for each college:-
<?php
$Name = mysql_real_escape_string(trim($_POST['Name']));
$schoollogo = mysql_real_escape_string(trim($_POST['schoollogo']));
$Motto = mysql_real_escape_string(trim($_POST['Motto']));
$Description = mysql_real_escape_string(trim($_POST['Description']));
$Type = mysql_real_escape_string(trim($_POST['Type']));
$ReligiousAffiliation = mysql_real_escape_string(trim($_POST['ReligiousAffiliation']));
$OtherPartnerships = mysql_real_escape_string(trim($_POST['OtherPartnerships']));
$GenderAdmission = mysql_real_escape_string(trim($_POST['GenderAdmission']));
$TermType = mysql_real_escape_string(trim($_POST['TermType']));
$EntranceExam = mysql_real_escape_string(trim($_POST['EntranceExam']));
$EntranceExamDate = mysql_real_escape_string(trim($_POST['EntranceExamDate']));
$TotalEnrolled = mysql_real_escape_string(trim($_POST['TotalEnrolled']));
$collegewebsite = mysql_real_escape_string(trim($_POST['collegewebsite']));
$ContactInfo = mysql_real_escape_string(trim($_POST['ContactInfo',
$CampusLocations = mysql_real_escape_string(trim($_POST['CampusLocations']));
$Certifications = mysql_real_escape_string(trim($_POST['Certifications']));
$Diplomas = mysql_real_escape_string(trim($_POST['Diplomas']));
$AssociateDegrees = mysql_real_escape_string(trim($_POST['AssociateDegrees']));
$MastersDegrees = mysql_real_escape_string(trim($_POST['MastersDegrees']));
$DoctorateDegrees = mysql_real_escape_string(trim($_POST['DoctorateDegrees']));
$SpecialDegreePrograms = mysql_real_escape_string(trim($_POST['SpecialDegreePrograms']));
$Accreditation = mysql_real_escape_string(trim($_POST['Accreditation']));
$CostofTuitionLocal = mysql_real_escape_string(trim($_POST['CostofTuitionLocal']));
$CostofTuitionForeign = mysql_real_escape_string(trim($_POST['CostofTuitionForeign']));
$Housing = mysql_real_escape_string(trim($_POST['Housing']));
$AcceptanceRate = mysql_real_escape_string(trim($_POST['AcceptanceRate']));
$CoE = mysql_real_escape_string(trim($_POST['CoE']));
$CoD = mysql_real_escape_string(trim($_POST['CoD']));
$ins = mysql_query("INSERT INTO Colleges (Name, schoollogo, Motto, Description,Type, ReligiousAffiliation, OtherPartnerships, GenderAdmission, TermType, EntranceExam, EntranceExamDate, TotalEnrolled, collegewebsite, ContactInfo, CampusLocations, Certifications, Diplomas, AssociateDegrees, MastersDegrees, DoctorateDegrees, SpecialDegreePrograms, Accreditation, CostofTuitionLocal, CostofTuitionForeign, Housing,AcceptanceRate, CoE, CoD)
VALUES ('$Name',
'$schoollogo',
'$Motto',
'$Description',
'$Type',
'$ReligiousAffiliation',
'$OtherPartnerships',
'$GenderAdmission',
'$TermType',
'$EntranceExam',
'$EntranceExamDate',
'$TotalEnrolled',
'$collegewebsite',
'$ContactInfo',
'$CampusLocations',
'$Certifications',
'$Diplomas',
'$AssociateDegrees',
'$MastersDegrees',
'$DoctorateDegrees',
'$SpecialDegreePrograms',
'$Accreditation',
'$CostofTuitionLocal',
'$CostofTuitionForeign',
'$Housing',
'$AcceptanceRate',
'$CoE',
'$CoD')") or die(mysql_error()) ;
if($ins)
{
echo "<br>".$Name."inserted";
$CollegeId = mysql_insert_id();
$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("\n", $text);
foreach ($textAr as $BachelorsDegrees)
{
mysql_query("INSERT INTO Colleges_Courses (CollegeId, BachelorsDegrees)
VALUES (".(int)$CollegeId.", '".mysql_real_escape_string(trim($BachelorsDegrees))."')") or die(mysql_error()) ;
}
}
else
{
echo mysql_error();
}
If you wanted to use multiple inserts, updating each field in turn (which would be very slow and serves no useful purpose here), then you can insert multiple times with a column value and insert it if the row already exists. In this case assuming you have an auto increment id field:-
<?php
$Name = mysql_real_escape_string(trim($_POST['Name']));
$schoollogo = mysql_real_escape_string(trim($_POST['schoollogo']));
$Motto = mysql_real_escape_string(trim($_POST['Motto']));
$Description = mysql_real_escape_string(trim($_POST['Description']));
$Type = mysql_real_escape_string(trim($_POST['Type']));
$ReligiousAffiliation = mysql_real_escape_string(trim($_POST['ReligiousAffiliation']));
$OtherPartnerships = mysql_real_escape_string(trim($_POST['OtherPartnerships']));
$GenderAdmission = mysql_real_escape_string(trim($_POST['GenderAdmission']));
$TermType = mysql_real_escape_string(trim($_POST['TermType']));
$EntranceExam = mysql_real_escape_string(trim($_POST['EntranceExam']));
$EntranceExamDate = mysql_real_escape_string(trim($_POST['EntranceExamDate']));
$TotalEnrolled = mysql_real_escape_string(trim($_POST['TotalEnrolled']));
$collegewebsite = mysql_real_escape_string(trim($_POST['collegewebsite']));
$ContactInfo = mysql_real_escape_string(trim($_POST['ContactInfo',
$CampusLocations = mysql_real_escape_string(trim($_POST['CampusLocations']));
$Certifications = mysql_real_escape_string(trim($_POST['Certifications']));
$Diplomas = mysql_real_escape_string(trim($_POST['Diplomas']));
$AssociateDegrees = mysql_real_escape_string(trim($_POST['AssociateDegrees']));
$MastersDegrees = mysql_real_escape_string(trim($_POST['MastersDegrees']));
$DoctorateDegrees = mysql_real_escape_string(trim($_POST['DoctorateDegrees']));
$SpecialDegreePrograms = mysql_real_escape_string(trim($_POST['SpecialDegreePrograms']));
$Accreditation = mysql_real_escape_string(trim($_POST['Accreditation']));
$CostofTuitionLocal = mysql_real_escape_string(trim($_POST['CostofTuitionLocal']));
$CostofTuitionForeign = mysql_real_escape_string(trim($_POST['CostofTuitionForeign']));
$Housing = mysql_real_escape_string(trim($_POST['Housing']));
$AcceptanceRate = mysql_real_escape_string(trim($_POST['AcceptanceRate']));
$CoE = mysql_real_escape_string(trim($_POST['CoE']));
$CoD = mysql_real_escape_string(trim($_POST['CoD']));
$ins = mysql_query("INSERT INTO Colleges (Id, Name)
VALUES (NULL, '$Name')";
if($ins)
{
echo "<br>".$Name."inserted";
$CollegeId = mysql_insert_id();
$ins = mysql_query("INSERT INTO Colleges (Id, schoollogo)
VALUES (".(int)$CollegeId.", '$schoollogo') ON DUPLICATE KEY UPDATE schoollogo = VALUES(schoollogo)";
$ins = mysql_query("INSERT INTO Colleges (Id, Motto)
VALUES (".(int)$CollegeId.", '$Motto') ON DUPLICATE KEY UPDATE Motto = VALUES(Motto)";
$ins = mysql_query("INSERT INTO Colleges (Id, Description)
VALUES (".(int)$CollegeId.", '$Description') ON DUPLICATE KEY UPDATE Description = VALUES(Description)";
$ins = mysql_query("INSERT INTO Colleges (Id, Type)
VALUES (".(int)$CollegeId.", '$Type') ON DUPLICATE KEY UPDATE Type = VALUES(Type)";
//etc
$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("\n", $text);
foreach ($textAr as $BachelorsDegrees)
{
mysql_query("INSERT INTO Colleges_Courses (CollegeId, BachelorsDegrees)
VALUES (".(int)$CollegeId.", '".mysql_real_escape_string(trim($BachelorsDegrees))."')") or die(mysql_error()) ;
}
}
else
{
echo mysql_error();
}
You can use multi-query to combine multiple sql queries into one single query.
Example with Multi-Query
$mysqli = new mysqli("example.com", "user", "password", "database");
$sql = "INSERT INTO table VALUES ('My First Table'); ";
$sql.= "INSERT INTO table VALUES ('My Second Table'); ";
$mysqli->multi_query($sql);

display post from html in following php script

I have a html page that posts to mysql database through a php script. How do I get the information that was entered in the html page to display after 1 record created?
<?php
$link = mysqli_connect('****', '****', '****', 'orders');
$sequence = $_POST['sequence'];
$items_count = $_POST['items_count'];
$total = $_POST['total'];
$payment_type = $_POST['payment_type'];
$sql="INSERT INTO orders (sequence,items_count,total,payment_type)
VALUES
('$sequence','$items_count','$total','$payment_type')";
if (!mysqli_query($link,$sql)) {
die('Error: ' . mysqli_error($link));
}
echo '1 record created';
mysqli_close($link);
?>
In the page that is supposed to display the posts, have another query
$sql = "SELECT sequence,items_count,total,payment_type FROM orders";
and I'm not sure if it's the right mysqli function, but after you retrieve the data from mysql as an array (mysqli_fetch_array ?) - you have to iterate through the returned results.
foreach($fetched_row as $row){
echo "<pre>"; print_r($row); echo "</pre>"
}
Which, you'll obviously want to use your own HTML - and the $row will be an associative array with the column names as the keys --
You need to add this code on the page where your fields will be displayed.
<?php
$last_record_id = mysql_insert_id();
$query = "SELECT * FROM <tablename> WHERE <$table_primary_key_id> = '$last_record_id'";
$result = mysqli_query($dbcon, $query);
$row = mysqli_fetch_array($result)
?>
Then fetch each field in separate variable like $price = $row['price'] and display them. You don't need looping because there is only one record to fetch and display.

Categories