I have a table whose primary key is a column named St_ID. I want to update another column in that same (ID) using values stored in an array. But when I try the code below, the result is a new record with an St_ID value of '0' and all other columns are empty.
Note, courseID is a value chosen through a drop down list. Do you have any idea where I went wrong?
for ($i = 0; $i < $count; $i++){
$Student = $foo[$i];
$res = mysql_query("SELECT St_ID FROM student WHERE St_ID='$Student' ");
while($row = mysql_fetch_array($res))
{
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
}
}
if (!mysql_query($sql,$connectdb))
{
die ('Error :'.mysql_error());
}
echo "The Students are add to the course <br />";
Here simplified code, with only one query
$where = "'".implode("','", $foo)."'";
$res = mysql_query("UPDATE student set ID = courseID WHERE St_ID IN ($where)")
or die('Error :'.mysql_error());
echo "The Students are add to the course <br />";
you select St_ID but try to insert courseID
in this line
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
SELECT St_ID FROM student WHERE St_ID='$Student'
INSERT INTO student (ID) VALUES ...
If you want to update that record you chose, you must use the UPDATE sql command instead;
UPDATE student
SET ID=...
WHERE St_ID='$Student'
Related
I'm trying to insert multiple records from a text box into a mysql table.
If I enter more than 2 records, it's inserting duplicates.
Here's the code.
What am I doing wrong?
Some more info
Table info
id (int) primary auto_increment
email (varchar)
imei (varchar)
date_ordered (datetime)
status(varchar)
Since it's only the beginning, I have no problems with changing the table structure.
$email = $_SESSION['email'];
$now = time():
$status = "1";
$imeis = $_POST['imeis'];
$row = explode("\n", $imeis);
foreach ($row as $key => $imei)
{
$imei = mysql_real_escape_string($imei);
$query = "SELECT * FROM orders WHERE imei = '$imei'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) == 0)
{
$query1 = "INSERT IGNORE INTO orders (email, imei, date_ordered, status) VALUES ('$email', '$imei', '$now', '$status')";
$result1 = mysqli_query($link, $query1) OR die("fml");
if ($result1)
{
echo "Added $imei<br>";
}
}
else
{
echo "<B>$imei</B> already there<br>";
}
}
It looks like you want each value of imei to be unique in your table. It;s a guess, but it looks like what you're doing.
You do that in SQL by defining the imei column to be unique: that is, by creating a unique index on it. Your present table has an id as a unique (primary) key. You can easily create another one.
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 with (id, stock_code, batch_code, qty).
id is primary key and auto increment value.
stock_code and batch_code is combine unique. Now I want update in insert query when stock_code and batch_code is duplicate
example
id stock_code batch_code qty
1 r001 b001 100
2 roo1 b002 100 //it should be insert
3 roo1 boo1 120 //it should be update in first row
4 roo2 boo1 130 //it should be insert
5 roo1 boo2 289 //it should be update in second row
$stockcode = "some value";
$batchcode="some value";
$qty = some value;
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query22 = "select * from table where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";
$result22 = mysqli_query($con,$query22) or die (mysqli_error());
$num22 = mysqli_num_rows($con,$result22);
if($num22 > 0) {
$query222 = "update table set qty='".$qty."' where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";
$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}
else {
$query222 = "insert into table(stock_code, batch_code, qty) values('".$stockcode."','".$batchcode."','".$qty."') ";
$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}
Try use
ON DUPLICATE KEY UPDATE
You can read the reff here http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You are looking for INSERT ON DUPLICATE KEY UPDATEhttp://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
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());
?>
How do insert multiple rows into a mysql table, with one column remaining constant, and the other as an array.
//inserted profession into professions table, return id
$new_profession_id = mysql_insert_id();
$qualification_array = array();
foreach ($_POST['qualification'] as $qual){
array_push($qualification_array, $qual);
}
$query = "???
now how would I insert this into the profession_has_qualification table? its got me stumped...
You can do like this:
$new_profession_id = mysql_insert_id();
foreach ($_POST['qualification'] as $qual){
mysql_query("insert into TableName set pid = $new_profession_id, qualification = '" . mysql_real_escape_string($qual) . "'");
}