How to insert a custom inscription ID of a user in mysqli? - php

I'm working on a school manager script.
I don't know how to insert a custom unique id of subscription...
I just use this function to show it's unique subscription's id when showing his/her full informations from the database:
$year = date('Y');
$ID = substr($student->dateNaissance,8,10).$student->id_etudiant."/".$year;
The function is combined of 3 things:
The 2 last digits of the year of birth (example: 01/01/1981.. i take only this -->81 using the substr function)
The row id from the table on the database (ex: 50).
And the year of subcription(example: 2013)
all that gives me , for example, as result 8150/2013
what i want here is when inserting the student data into the database , i want this unique ID to be inserted as well..
The problem here is i don't know how to get the last id of a row !
Yeah, I tried to insert the student data and then update the id_subscription using this:
if(isset(....){
......
$mysqli->query("INSERT INTO table (a,b,c, ...etc) VALUES('','',''..etc)");
$year = date('Y');
$mysqli_query("SELECT * FROM table_name");
$studentID = $mysqli_insert_id();
$ID = substr($student->dateNaissance,8,10).$ID."/".$year;
$mysqli->query("UPDATE table_name SET id_subscription = $ID");
}
But its not working :\
By the way: in my table Im using an auto_increment id + the subscription_id in which i want to insert the customized id I showed above.

Assuming that row id is an auto_increment field, then you'd have to do it in two stages:
start transaction
insert everything into the DB EXCEPT your id field
use last_insert_id() to get the mysql-generated ID field
build your own id field
update the record with this new id
commit the transaction.

On Database Structure:
1. you can use auto-incremented primary key in your table and store the data(student_id) as a seperate column(recommended).
On getting 'the last id of a row':
1. Use mysql_insert_id() .. check this out

Related

How to display both old and new values of particular column in sql on html using php?

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

Inserting data into multiple tables not functioning correctly

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

Add a new record to database after checking value

I am inserting data into a database fine with the user entering a reference number eg 1234. Can I change my insert to not require the user to input the value and for the last value entered to be checked and then the reference number being inserted be incremented by one and then inserted with the other data. Bit of a new bee. Here is my current code
$Reference_No = $_POST['Reference_No'];
$Property_Name = $_POST['Property_Name'];
$Property_Area = $_POST['Property_Area'];
mysql_query("INSERT INTO properties (Reference_No, Property_Name, Property_Area)
VALUES ('$Reference_No', '$Property_Name', '$Property_Area')");
You need to make the Reference_No an AUTO_INCREMENT.
Step 1:Create table
CREATE TABLE properties (
Reference_No int AUTO_INCREMENT ,
Property_Name varchar(255),
Property_Area varchar(255),
PRIMARY_KEY (Reference_No)
)
Step 2 : Set the start for auto increment of primary key if you like
ALTER TABLE properties AUTO_INCREMENT=1234;
Step 3: Insert the data into the table
INSERT INTO properties (Property_Name, Property_Area)
VALUES ('$Property_Name', '$Property_Area')");
interogate the database for the Reference NO (where property name matches if you need it)
$reference_no_query = mysql_query("SELECT Reference_No FROM properties WHERE Property_Name = $Property_Name");
pull the Reference No out of the database
$Reference_no = mysql_fetch_array($reference_no_query)
display the Reference no
echo $Reference_no('Reference_no');
you can (and should) tie the data to a variable then echo the var like this:
$Reference_no_display = $Reference_no('Reference_no');
then display it directly from the variable anywere and as many times as you want in the page below the query:
echo $Reference_no_display;
This seems to do the trick for the final bit
printf("Last inserted record has id %d\n", mysql_insert_id());

How do i reset auto increment column in database with php page?

Suppose i have a database that store report from employees which first column is reportID(auto increment), staffID,name,department and so on.
Everytime i submit i report from my php page it will display increment number (reportID) in my php page. So lets say i got 3 report ID stored in the table, i want to delete three record, and then add 1 new record to the table, but now the reportID display as 4 because the past three reportID are 1,2,3, so how do i reset the new record to 1 instead of 4? is there a code to reset it?
This is my deletereport.php
<?php
include('adminconfig.php');
include('config.php');
$reportID = mysql_real_escape_string($_GET['id']);
$sql="DELETE FROM `report` WHERE `reportID`='$reportID'";
$result=mysql_query($sql);
if(!$result){
die('invalid query:'.mysql_error());
}
else
?>
<p style="font-family:arial;color:#0066CC;font-size:30px;">One row deleted...</p>
<?php
header('Refresh:3; url=viewreportdb.php');
die;
?>
You have to truncate the table to reset auto incremented values
or just
ALTER TABLE yourtable AUTO_INCREMENT = 1
similar discussion here
Auto Increment after delete in MySQL
Probably don't want to reset and just use auto-increment.
query following from PHP:
ALTER TABLE tablename AUTO_INCREMENT = 1

Set UNIQUE priorities ON DUPLICATE KEY

I have the following table
id year name activation
1 2013 TEST 1
id A_I
year, name UNIQUE
name, activation UNIQUE
I use this query to INSERT/UPDATE data:
INSERT INTO LISTE_DATI
(year, name, activation)
VALUES
('$varray[1]', '$varray[2]', '$varray[3]')
ON DUPLICATE KEY UPDATE
year= '$yr',
name= '$na',
activation= '$act'
If I send this data to the table:
$yr = 2014
$na = TEST
$act = 0
the query INSERT data in the table. This is ok for me!
If I send this data to the table:
$yr = 2015
$na = TEST
$act = 1
the query UPDATES the first row (2013/TEST/1) in the table.
In this case I'd like to have an INSERT too.
How can I adjust it?
You are telling your INSERT query, that when it finds a duplicate (UNIQUE) key, to instead update that row.
You are inserting (2012, 'TEST', 1). This is a duplicate key; the name, activation key, your 2nd UNIQUE key! You already have a row with 'TEST', 1; the row with id=1.
The INSERT query updates that row, since it's a duplicate key.
You need to modify the keys on your table so that it reflects the data you want in it. What do you want the INSERT query to consider a duplicate? Create your UNIQUE keys based on that.

Categories