insert values not working in mysqli - php

I have created two tables, employee and department. Now, in the department table, I assigned a foreign key and a PK is assigned for the employee table. If view data, Ii can join the table.
How to write the query in PHP for insert and update?
My query:
?php
include "connect.php";
if(isset($_POST["submit"]))
{
$fname = $_POST["fname"];
$dept = $_POST["dept"];
$result = mysqli_query($mysqli, "INSERT INTO employee ( fname, department)
(SELECT fname, department FROM employee LEFT JOIN department ON employee.id=department.dept_id) values ( '$fname', '$dept')");
if($result)
{
echo "<script>alert('New employee register successfully!')</script>";
echo "<script>window.open('register.php','_self')</script>";
}
else
{
echo "<script>alert('something went wrong!')</script>";
}
}
?>

$result = mysqli_query($mysqli, "INSERT INTO employee (`fname`, `dept`)
VALUES ('$fname','$dept')");
if($result)
{
echo "<script>alert('New employee register successfully!')</script>";
echo "<script>window.open('register.php','_self')</script>";
}
// You Forget ( `` ) sign in values

Related

How can I insert a constant value and a select value from other table?

I want to insert a data from the other table and to another. But first I need to include also the latest id inserted from the parent table. Anyone can help me out?
<?php
$insert1 = "INSERT INTO purhcase_order
(Supp_ID, Approved_by, Prepared_by, Estemated_cost)
VALUES ($suppname, '$appname', '$prepname', $total_cost)";
// $resultToinsert1 = mysqli_query($connector, $insert1);
// header('location: purchase-order_staff.php');
if (mysqli_query($connector, $insert1)) {
$lastInsertedId = mysqli_insert_id($connector);
$insert2 = "INSERT INTO purchase_order_product
(Pur_ord_id, Product_ID, Quantity, Estimated_amount)
SELECT $lastInsertedId, A.Product_ID, B.Qty_requested as
Quantity, (B.Qty_requested * C.Product_price ) as
Estimated_amount from
ware_house_product A, purchase_request_product B,
supplier_product C, purchase_request D, supplier E
WHERE A.Product_ID = B.Product_ID and
A.Product_ID=C.Product_ID AND C.Supp_ID=E.Supp_ID
AND E.Supp_ID='$suppname' AND
D.Pur_req_id='$Purchase_request_id'";
$resultToinsert2 = mysqli_query($connector, $insert2);
if ($resultToinsert2 == TRUE) {
header('location: purchase-order_staff.php');
}else {
echo "Data is not inserted";
}
}else {
echo "Data is not inserted";
}
}
}
?>

PHP Selecting from table 1 and inserting in table 2 with id return be 0 on table 2

first sorry for my english. I have a problem on my isset Here's the codes:
PHP:
if(isset($_POST['insert'])) {
$insert = $_POST['insert'];
}
{
require('./clanconfig.php');
$cln = $_POST['clanname'];
$cms = $_POST['mesa'];
$checkup = "SELECT id FROM clan WHERE cname='$cln'";
$upsql = mysqli_query($conn, $checkup);
while($srcclan=mysqli_fetch_array($upsql) )
{
$checked = $srcclan['id'];
}
$sql2 = "INSERT INTO clanrequest (clanid, plname, message, playerid) VALUES('$cln', '$uname', '$cms', '$player_id')";
$sql3 = mysqli_query($conn, $sql2) or die();
}
mysqli_close($conn);
Problem is While searching on table1 with a Post value it's okay but while inserting on table 2 with a id of table 1 and on table 2 adding but value is only 0 on id column
Html:
<form class="clan-form-join action="clanjoin.php" method="post">
<?php
require('./clanconfig.php');
$sql = "SELECT * FROM clan";
$sql2 = mysqli_query($conn, $sql);
echo "<html>";
echo "<body>";
echo "<select name='clanname'>";
while($sonuct=mysqli_fetch_array($sql2) )
{
$cnamer = $sonuct['cname'];
echo '<option value=" '.$cnamer.'">'.$cnamer.'</option><br />';
}
echo "</select>";
echo "</body>";
echo "</html><br>";
echo'<b>Message</b><br><textarea name="mesa" rows=3 cols=40></textarea><br/>';
echo'<input type="submit" name="insert" class="clanbutton" value=" Send Application ">';
?>
</form>
Here's the html codes, i select the details of clan in a clan table and when member select the clan name and insert the button the codes sent with a clan name selected like test clan in isset value and in the isset select the id of clan selected on option value clan name on table clan and return to insert clan request with name,id of player and where id of clan the problem is id of clan adding automatically 0 without add real id of clan
All the code for inserting should be inside the if (isset($_POST['insert'])). You only have the variable assignment there (and you never even use that variable), you have the rest of the code in a separate block (there's no purpose to putting it in a block).
if(isset($_POST['insert'])) {
$insert = $_POST['insert'];
require('./clanconfig.php');
$cln = $_POST['clanname'];
$cms = $_POST['mesa'];
$checkup = "SELECT id FROM clan WHERE cname='$cln'";
$upsql = mysqli_query($conn, $checkup);
while($srcclan=mysqli_fetch_array($upsql) )
{
$checked = $srcclan['id'];
}
$sql2 = "INSERT INTO clanrequest (clanid, plname, message, playerid) VALUES('$cln', '$uname', '$cms', '$player_id')";
$sql3 = mysqli_query($conn, $sql2) or die();
mysqli_close($conn);
}

Insert into Two table having the same database but shaing the same id

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

Why I have empty record in MySQL?

In our system they asked us to add research interest but when we add new user, we should assign an interest to him/her. It's adding successfully to the database table, we have problem which is we get zero record in the interest_id database table, why?
Here all research interest added successfully to database:
As you see in picture below when admin add a new user he chooses multiple interests and assign them to a user:
Here is screenshot of user profile as you can see interests that admin assigned to new user:
The problem is that it don't write interest id to database?
Below you can see the codes and SQL table:
<p>
<label>Research Areas</label>
<select name="interest_id[]" class="small-input" multiple>
<?php
$query = "SELECT * FROM research_interest ORDER BY name ASC";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_object($result))
{
?>
<option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
<?php
}
?>
</select>
</p>
Here is also codes for MySQL:
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'user_add':
$user_id = mysqli_real_escape_string($link,$_POST['user_id']);
$email = mysqli_real_escape_string($link,$_POST['email']);
$password = rand_pass(8);
$title_id = intval($_POST['title_id']);
$user_type_id = intval($_POST['usertype_id']);
$department_id = intval($_POST['department_id']);
$view_publication = mysqli_real_escape_string($link,$_POST['publication']);
$referee = mysqli_real_escape_string($link,$_POST['referee']);
$gender = mysqli_real_escape_string($link,$_POST['gender']);
$creation_date = date('Y.m.d');
//Interest
if(!empty($_POST['interest_id']) && is_array($_POST['interest_id'])) {
foreach ($_POST['interest_id'] as $interest)
{
$query = "INSERT INTO user_interest (user_id, interest_id)
VALUES ('$user_id', '$interest')";
$result = mysqli_query($link,$query);
}
}
//SQL Query
$query = "INSERT INTO user (user_id, email, title, user_type_id, department_id, referee, gender, password, view_publication, creation_date)
VALUES ('$user_id', '$email', '$title_id', '$user_type_id', '$department_id', '$referee', '$gender', '$password', '$view_publication', '$creation_date')";
$result = mysqli_query($link,$query);
echo '<script type="text/javascript">';
echo 'window.location = "mail.php?action=user_mail&user_id='.$user_id.'"';
echo '</script>';
break;
}
}
And this is a user_interest table shows that these three research IDs assign to user 1
but here it show that interest_id is zero , it don't shows ids of research interest that added to user 1
You are not including interest_id in your Insert query to the users table. So the table is assigning a default value of 0.
You're not inserting anything into the "interest_id" column in the second query so it's defaulting to zero. It looks like you're trying to set up a many to many relationship (one user can have many interests and one interest can belong to many users). In that case you'll need to set up a junction table (http://en.wikipedia.org/wiki/Junction_table) to handle the relationship.

I want to insert data from a single form into multiple table both table contains relations

I am new to php and trying to learn. I m also trying to make an web application "school management system".
I am getting problem while i am inserting records in student and parents table from the same form, the form is ok and its inserting record in student table but not in parents table.
in parents and student table student_id is common and in student table student_id contain primary key and in parents table it contain foreign key.
my code is given below:
<?php>
if(isset($_POST['submit'])){
$reg = $_POST['reg_no'];
$s_name = $_POST['student_name'];
$s_father = $_POST['student_father'];
$p_last_name = $_POST['parent_lastname'];
$s_birth = $_POST['student_birth'];
$p_phone = $_POST['parent_phone'];
$p_address = $_POST['parent_address'];
$school_name = $_POST['school_name'];
$batch = $_POST['session_batch'];
//filtering variables
$reg_no = mysql_real_escape_string($reg);
$student_name = mysql_real_escape_string($s_name);
$student_father = mysql_real_escape_string($s_father);
$parent_last_name= mysql_real_escape_string($p_last_name);
$student_birth = mysql_real_escape_string($s_birth);
$parent_phone = mysql_real_escape_string($p_phone);
$parent_address = mysql_real_escape_string($p_address);
$school = mysql_real_escape_string($school_name);
$batch = mysql_real_escape_string($batch);
//connecting to db by including db file
include_once('include/dbconnect.php');
$db_select = mysql_select_db($server_db_name,$db_connect);
if ($db_connect)
{
$student_query = "INSERT INTO students (school_id, session_id, student_name,
student_father, student_birthdate, registration_no) VALUES
('$school','$batch','$student_name','$student_father','$student_birth','$reg_no')";
$s_query = mysql_query($student_query) or DIE ("error. while inserting records in
student");
/* here im trying to select student_id which is inserted above to insert data in
parents table*/
$id_query = mysql_query("SELECT * FROM students WHERE student_id = $student_name
LIMIT 1") or DIE ("Could complete the id query");
while ($id_result = mysql_fetch_array($id_query))
{ $s_id = $id_result['student_id'];
$parent_query = "INSERT INTO parents (school_id, student_id, parent_name,
parent_lastname, parent_phone, parent_address)
VALUES('$school','$s_id','$student_father','$parent_last_name',
'$parent_phone','$parent_address')";
$p_query = mysql_query($parent_query);
if (!$parent_query) { echo "error. while inserting records in student"; }
}
mysql_close($db_connect);
header('location:admin.php?student');
}
else {
echo "Error While Connecting to server";
}
}else {
header('location:admin.php?error');
}
?>
Like JOE LEE has mentioned in above snippet,
$generated_key=mysql_insert_id();
// this line of code actually returns the auto generated id, of course I am guessing you want the auto incremented value from the student table for the parent table.
find id u Last inserted, use mysql_insert_id()
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %d\n", mysql_insert_id());
?>

Categories