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')";
Related
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);
I need to insert each checkbox to row in MySql.
At the moment i am able to catch only one checkbox, but I usually have them 1 - ... who knows how many..
All my checkboxes come from Db like that :
<input type="checkbox" name="lisateenus[]" value="<?php echo $row["id"]; ?>">
On insert it should take the "page id" what is created and after that insert checkbox values to table.
it gets all needed ID-s but it inserts only one checkbox what is checked..
$result = mysqli_query($con,$query);
if($result) {
$last_id = $con->insert_id;
$error = "Uus Teenus lisatud! ". $last_id;
$checkBox = implode(',', $_REQUEST['lisateenus']);
$query="INSERT INTO lisateenuse_seos (p_id, l_id, lisaja) VALUES ($last_id,'" . $checkBox . "','1')";
mysqli_query($con, $query) or die (mysql_error() );
echo "Complete";
} else {
$error = "Teenuse lisamine ei õnnestunud";}
So everything is working exept that it only inserts one row, but 3 rows are checked and should be inserted..
"each checkbox has his own ID (different) only last_id and lisaja have the same id, so each checkbox should be separate row in MySql table (after insert)"
In that case, you actually don't want to implode your checkboxes, but go through with a foreach on them:
foreach ( $_REQUEST['lisateenus'] as $somevalue ) {
$query="INSERT INTO lisateenuse_seos (p_id, l_id, lisaja) VALUES ('$last_id' ,'" . $somevalue . "','1')";
mysqli_query($con, $query) or die (mysql_error() );
echo "Complete";
}
This should insert a new row for each checked checkbox. Using implode actually makes a single string from the whole array, which then you insert only once. With foreach, you send and insert command to the sql for each ( :D ) checked checkbox.
(I added some extra quotes for the good cause.)
I want to create a php code that will insert value to to tables but i want table one "id" and table two "product_id" to be the same thing. this is my below code that insert values to the database but table one "id" do not correspond to table two "product_id"
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['name'];
$image = $_POST['image'];
$price = $_POST['price'];
$stock = $_POST['stock'];
$description = $_POST['description'];
$status = $_POST['status'];
require_once('dbConnect.php');
$sql ="SELECT id FROM product ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$imagename = "$id.png";
$path = "uploads/$id.png";
$storage = "$id.png";
$actualpath = "http://localhost/markeet/$path";
$sql = "INSERT INTO product (name,image,price,stock,draft,description,status,created_at,last_update) VALUES ('$name','$storage','$price','$stock','0','$description','$status','','');";
$sql .= "INSERT INTO product_category (product_id, category_id)
VALUES ('', '$stock');";
if ($con->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
In your code you use multi_query() to run your both queries right after each other.
I suggest the following:
// Insert product
$queryInsertProduct = "INSERT INTO product (name,image,price,stock,draft,description,status,created_at,last_update) VALUES ('$name','$storage','$price','$stock','0','$description','$status','','');";
/**
* #TODO:
* 1. Alter table `product_category` and do `product_id` to match the field
* type from table `product`.`product_id`
* 2. Alter table `product_category` and create its own ID primary key field,
* which can be different from `product_id`
*/
$queryInsertProductCategory = "INSERT INTO product_category (product_id, category_id)
VALUES ('', '$stock');";
// Run here first query to insert product $queryInsertProduct using mysqli_query()
// Take ID of the insert product using function mysqli_insert_id()
// Run second query $queryInsertProductCategory and provide the id from new insert product to the product_id field
Use the MySQL LAST_INSERT_ID() function to get the auto-increment ID that was assigned in the most recent INSERT.
$sql = "INSERT INTO product (name,image,price,stock,draft,description,status,created_at,last_update) VALUES ('$name','$storage','$price','$stock','0','$description','$status','','');";
$sql .= "INSERT INTO product_category (product_id, category_id)
VALUES (LAST_INSERT_ID(), '$stock');";
BTW, the return value of $con->multi_query() is just the success of the first query. You need to use $con->next_result() to get the success of the second query.
You need to get that inserted ID by using function mysqli_insert_id
I have a table populated by a MySQL table, and I am trying to insert the selected rows from the table into another table.
The table look like below:
.
There are first three fields in the table are coming from two other tables depending on the Field values.
And the drop down selections are provided by user using:
$sql = "SELECT project_proposals.id, project_proposals.title, project_proposals.description, project_proposals.academicname, flux_student_records.studentname, flux_student_records.id, flux_student_records.programme, flux_student_records.academicdiscipline FROM project_proposals JOIN flux_student_records ON project_proposals.academicdiscipline = flux_student_records.academicdiscipline
WHERE project_proposals.academicdiscipline = '$academicdiscipline' AND flux_student_records.studentname = '$studentname'";
$retval = mysql_query($sql) or die(mysql_error());
What will be the best way to insert these multiple selected rows into another table please? Thanks.
"select into" is the way to go.
SELECT into YourNewTable select project_proposals.id, project_proposals.title, project_proposals.description, project_proposals.academicname, flux_student_records.studentname, flux_student_records.id, flux_student_records.programme, flux_student_records.academicdiscipline FROM project_proposals JOIN flux_student_records ON project_proposals.academicdiscipline = flux_student_records.academicdiscipline
WHERE project_proposals.academicdiscipline = '$academicdiscipline' AND flux_student_records.studentname = '$studentname'";
Hope you find this usefull.
You can loop trough an post and then do some thing with that information.
So for example:
<?php
function readDataForwards($dbh) {
$sql = 'SELECT * FROM yourdb';
try {
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
#insert the data into another database
#you can also filter some duplicated items that you already
#have in the database
}
$stmt = null;
}
catch (PDOException $e) {
print $e->getMessage();
}
}
?>
this would output: the rows in the database
but it could also insert the rows into your database.
I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.