inserting in mysqli is not working - php

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.

Related

How to have 2 insert queries on a single php file

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");

mysql insert statement inside a while statement adds only 1 record

I have this code (refer below)
$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);
while($row = mysqli_fetch_assoc($result)){
$itemid = $row['id'];
$itemname = $row['itemname'];
$itemdesc = $row['itemdesc'];
$brand = $row['brand'];
$serialno = $row['serialno'];
$nostock = $row['nostock'];
$price = $row['price'];
$onsale = $row['onsale'];
$poster = $row['poster'];
$thedate = $row['thedate'];
$sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
$result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
return $result;
}
as you can see from the above codes, it will first pull all the data from db table named "records" and then put each row into there corresponding variable and then insert the stored data (those data that has been pulled from db table name "records" and stored on there corresponding variable) to db table named "backupp". Now, the problem is, it only add one record to backup (the record that has been pulled first) which supposedly it should add all the pulled record from db table named records to db table named backup. why?? any suggestions, recommendations, clues and ideas would be greatly appreciated. Thank you!
PS: its like export and import to other table with same structure but I have my own reason why I want to do it this way and assume I already successfully connected to a database ($this->db) called "inventory" and there is db table name there such as "records" and "backupp" with same structure.
And you can easily backup same table this way: INSERT INTO backupp SELECT * FROM records
You have a return statement inside the while loop causing it to exit after one iteration.
Remove the return $result; line and it should work.
change your code into this (see below).
$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);
$x = 0;
while($row = mysqli_fetch_assoc($result)){
$itemid = $row['id'];
$itemname = $row['itemname'];
$itemdesc = $row['itemdesc'];
$brand = $row['brand'];
$serialno = $row['serialno'];
$nostock = $row['nostock'];
$price = $row['price'];
$onsale = $row['onsale'];
$poster = $row['poster'];
$thedate = $row['thedate'];
$sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
$result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
$x++;
}

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

PHP Variable in Select Statement

I've written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the "name" from the select name...
I've tried nearly everything, but nothing gave me the right result.
I know that the normal thing how I can use variables in a statement like ("'. $var .'") won't work.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID OF THE CURRENT CONTACT
$user = $_GET["user"]; //ID OF THE CURRENT USERS
$query = mysql_query("SELECT name FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->name;
$retval = trim($retval);
echo $retval;
?>
This is much easier isn't it?
$sql_insert =
"INSERT INTO customers (
`name`,
`address`,
`email`,
`phone`
)
VALUES (
'$name',
'$address',
'$email',
'$phone'
)";
Is it this you're looking for? Even your question in German isn't that clear to me :
$field = 'name';
$query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->$field;
You can usi it something like this. Currently i assume you get only one row back and want to use only one field.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
//Use variable inside closures `` and just in case escape it, depends how you get variable
$query = mysql_query("SELECT `".mysql_real_escape_string($variable)."` FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
if (!$query) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query); //Retriev first row, with multiple rows use mysql_fetch_assoc
$retval = $row['0']; //Retriev first field
$retval = trim($retval);
echo $retval;
?>
Please post in English. Everyone else does.
Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
Have you considered using PDO?
I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...
$fields = "name, age";
$sql = "SELECT $fields FROM table";
$sql = "SELECT {$fields} FROM table";
$sql = "SELECT ".$fields." FROM table";
NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.
// assuming $_POST['fields'] looks something like array('name','age','hack');
$allowed = array('name', 'age');
$fields = array();
foreach ($_POST['fields'] as $field) {
if (in_array($field, $allowed)) {
$fields[] = $field;
}
$fields = implode(', ', $fields);
Wouldn't this work?
$result = mysql_fetch_array($query);
echo trim($result['name']);
You should never put a variable into field list.
If want a variable field name, select *
and then use your variable to fetch particular field
<?php
require_once 'config.php';
$id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
$query = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result);
//and finally
$fieldname = "name";
$retval = $row[$fieldname];
echo $retval;
?>

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