Is it possible to have a table and insert data n a single row on two different occasion? I mean, I have a table with five column and on first data submission, i want to record data on only just two field on that table, and in different data submission on that same row, I would want to record data on those 3 remaining column that haven't been recorded with any data. What method should i use? INSERT or UPDATE? Or neither?
Sorry for my bad english and confusing way of asking question.
Code:
$query = ("SELECT q1 FROM grades where studentnumber = '$_POST[studentnumber]' && subjectcode = '$_POST[subjectcode]' ");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result) ==1)
{
$sql=mysql_query("UPDATE grades SET q1 = '$_POST[q1]' where studentnumber = '$_POST[studentnumber]' AND subjectcode = '$_POST[subjectcode]'");
if($sql)
{
echo "<script type='text/javascript'>alert('Password successfully changed'); location.href = 'cvsu-sis_grades.php';</script>";
}
}
}
else
{
echo "<script type='text/javascript'>alert('Record Does not Exist'); location.href = 'cvsu-sis_grades.php';</script>";
}
i omitted some columns just to make the coed shorter but most likely it is the same. just a series of q1, q2, ...
The first query should be an INSERT, then you can get the last inserted id and do an UPDATE query
You can use INSERT for first two columns, and get your inserted id using mysql_insert_id() (only if your primary key column name is "id") and using this you can update your remaining three columns using UPDATE
First of all you have to make sure, that when you insert the 2 fields on your first INSERT, the fields you leave empty are allowed to be NULL!
You have to INSERTthe first data into the table and later on, when you want to add the remaining fields, you have to UPDATE that row. Make sure that, when you UPDATE, you are using a WHERE-constraint (e.g. with the 2 fields already entered), otherwise all rows will be updated!
Related
Is there a way to auto-increment in MYSQL after deleting a row from the database?
For example:
There is a table with 3 columns: StudentID, Student Name, and Contact details. Here StudentID will be the primary key which will keep incrementing after adding values in each column.
The PHP code will look as follows:
<?php
require_once "Delete_Form.php";
if ($_GET || id['id']) {
$id = mysqli_real_escape_string($db, $_GET['id']);
} else {
echo 'Value was not brought over';
}
echo $id;
$result = mysqli_query($db,"SELECT StudentID, StudentName, Contact FROM student WHERE
StudentID='$id'");
$row = mysqli_fetch_row($result);
$sql= "DELETE FROM `student` WHERE `student`.`studentID` = $id";
echo "<pre>\n$sql\n</pre>\n";
mysqli_query($db,$sql);
echo 'Success -Continue...';
return;
Once we delete an entry from the database the Auto-Incrementation of StudentID will mess up i.e if the last entry had a StudentID of 12 and then we delete the same then the next row we enter will have StudentID of 13.
We can always do ALTER TABLE `student` AUTO_INCREMENT = 1 which will reset it but that will solve the problem temporarily only.
Is there a way to add a PHP statement in the above code to reset auto increment whenever we delete a row?
Do it never.
Primary key in a table identifies the row uniquely during the whole table lifetime. Pay attention - TABLE lifetime, not ROW lifetime. The fact that the row was deleted changes nothing - the value identifies this deleted row nevertheless.
If you need rows enumeration without the gaps then create special column for this purposes or enumerate in a query.
PS. By the way, synthetic AI PK must be hidden for the user at all - this column destination is row identifying and foreign keys subsystem work. It must not have any additional meaning.
Let us assume there is a form which has a text field and a submit button.
Every time I type a text and submit it should be stored in the database and displayed in a table.
Additionally, when I again submit the form the old text in SQL column value should be overwritten with this new value and both values should be displayed in table rows.
So every time I do this I want old data and new data to be appended to table rows.
How to achieve this??
Instead of overwriting the data, why not create a new entry and mark it as active, such that to get the latest data using sql, you order by primary key desc limit 1. If you need the old data you ust get the previous entry.
We have very few information, but here is some idea to achieve it :
1/ Add an last field in your table and update it each time you add a new data, then when you display it just get all data and check the last field to see which one is the last :
So imagine this table :
Table data
===============================
id_data | id_user | data | last
When you display it for your user :
select * from data where id_user = :id_user order by last desc;
This way you will get the last one with last = 1 (true) first then the other.
And when you submit a new data :
// you update all old data as "old"
update data set last = 0 where id_user = :id_user;
// you create a new data
insert into data (id_user, data, last) values (:id_user, :data, 1);
2/ Add a field date so you know wich one are older than other
Table data
==================================
id_data | id_user | data | created
When you display it for your user :
select * from data where id_user = :id_user order by created desc;
This way you will get the data order by the created date with the last one first.
And when you submit a new data :
// you create a new data with the current date
insert into data (id_user, data, created) values (:id_user, :data, NOW());
This solution is better I think so you can have some "historic" of each data.
Is it what you are looking for?
why not just append it with a pipe character like so... "|entry_data" then just explode it when you need it.
var data_array = explode("|",data);
print_r(data_array);
If you want to show all changes only for some users then better to save you last value in main table and create new history table for changes.
table_history
id | id_row | field | before | after
In this case you can without additional query show last value for some users and all data for others.
In this structure you also can save multiple fields data if you need.
And believe me, saving previous value in your table will make you life is easy in future.
In given below code i update field with new one insert data and also append your new data with old I hope this help you
Form from which you insert and update data
if(isset($_POST['submit']) && $_POST['submit']){
$text_field = $_POST['text_field'];
$query ="SELECT * FROM `table_name`"; //replace with your table name
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
$data = $result[1];
if(count($result)){
$last_string = $data.','.$text_field;
$update= "UPDATE `table_name` SET `text`='".$last_string."'";
mysqli_query($conn,$update);
}else{
$query = "INSERT INTO `table_name`(`text`) VALUES ('".$text_field."')";
mysqli_query($conn,$query);
}
}
?>
<form action="" method="POST">
<input type="text" name="text_field">
<input type="submit" name="submit">
</form>
view of data which is inserted
<?php
$query ="SELECT * FROM `table_name`";
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
if(isset($result) && count($result)){
echo "<p>$result[1]</p>";
}
i want to get datas from a mySQL table and want to insert every row (that my query get) into another table.
With following code i get my Datas:
$cart = new Dbconn();
$query = new Dbconn();
if ($cart->pdo()) {
$cart->stmt("SELECT id, product FROM cart WHERE uid =:uid");
$cart->bindParam(':uid', Session::get('uid'));
$cart->exe();
}
After i get the data i want to insert it, with a while loop
while ($rowPay = $cart->fetch()) {
if ($query->pdo()) {
$query->stmt('INSERT INTO orders (products_id, order_id) VALUES(:uid, :products)');
$query->bindParam(':user_id', Session::get('uid'));
$query->bindParam(':products', $rowPay['product']);
$query->exe();
}
}
He get all Datas but insert only the first entry. Where is my mistake?
Greetings
If it insert only the first entry, then there is a problem with the parameters you try to insert.
You probably try to insert several rows with the same primary key.
I need to know where is the primary key in each table in order to help you more.
$payCart->fetch() fetches single row and $payCart->fetchAll() fetches all rows.
Try as this
while ($rowPay = $payCart->fetchAll(PDO::FETCH_ASSOC)) {
if ($query->pdo()) {
$query->stmt('INSERT INTO orders'
.'(products_id, order_id)'
.'VALUES(:uid, :products)');
$query->bindParam(':user_id', Session::get('uid'));
$query->bindParam(':products', $rowPay['product']);
$query->exe();}}
I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement
I have a form button that I need to do two different things, based on user input and whether that input already exists in my database. If the input DOES NOT exist, then the button will create a new record. If it DOES exist, then the existing record will be updated.
Here's my PDO query as it stands now:
/* First, we need to discover whether the Proposal No. entered already exists in the
database. If it doesn't, then a new record will be created. If
it does, then an existing record will be updated. */
$pNoExists = $con->prepare("SELECT ProposalNo FROM ptfp1");
$pNoExists->execute();
$row = $pNoExists->fetch(PDO::FETCH_ASSOC);
When I run $row = $pNoExists->fetch(PDO::FETCH_ASSOC); through a while loop, all of the values for the field are present. Now I just need some guidance on how to use that in my button setup. This is what I want to do:
if($_POST['ButtonPush'] && input doesn't exist) {
Create new record;
}
else {
Update existing record;
}
Simple, right? But it's eluding me.
Given what you have, I would do:
if($_POST['ButtonPush'] && array_search($all_values, $input_value)) {
Create new
}
else {
Update
}
However, like the comment above, you may want to simply add a where clause to your "SELECT" statement so you are not grabbing the entire database table contents every time. And, one could even convert the SELECT in to a SELECT COUNT to bring down the amount of data being requested.
You could use SELECT count(*) FROM ptfp1 WHERE ProposalNo = :input
Than check if the value you get is bigger than one. If it is, update it:
UPDATE ptfp1 set ... where ProposalNo = :input
else
INSERT INTO ptfp1(...) VALUES (...)
Assuming ProposalNo has a unique index in the table, you can do it all in one query:
INSERT INTO ptfp1 (ProposalNo, colA, colB, colC, ...)
VALUES (:ProposalNo, :colA, :colB, :colC, ...)
ON DUPLICATE KEY
UPDATE colA = VALUES(colA), colB = VALUES(colB), colC = VALUES(colC), ...
Documentation
Figured out an answer. Just use the user's input (stored in a session variable) in my SELECT statement:
$pNoExists = $con->prepare("SELECT ProposalNo FROM ptfp1 WHERE ProposalNo =
'".$_SESSION['ProposalNo']."'");
$pNoExists->execute();
$row = $pNoExists->fetch(PDO::FETCH_ASSOC);
And the button:
if($_POST['ButtonPush'] && !$row['ProposalNo']) {
Write new record;
}
else {
Update existing record;
}
Hiding in plain sight!