how to display auto increment data form mysql in php - php

In my university database project I have an auto increment field roll number in my SQL. What I want is that when new admission take place and a student record is inserted it displays all finds on same page including roll number. However despite my best efforts all it returns 0 in roll number.
Here is the code:
<?php
$con = mysqli_connect("localhost", "root", "") or die("conection error");
mysqli_select_db($con, "hamdard university") or die("dbase error");
if (isset($_POST['subbtn'])) {
$r = "SELECT RollNo FROM admission_form";
$result = mysqli_query($con, $r);
if (mysqli_query($con, $r)) {
$last_id = mysqli_insert_id($con);
}
$n = $_POST['txtname'];
$f = $_POST['txtfac'];
$s = $_POST['txtsem'];
$sql = "insert into admission_form(name,faculty,semester)values ('$n','$f','$s')";
mysqli_query($con, $sql);
echo "<table border=1>
<th>RollNo</th>
<th>Name</th>
<th>Faculty</th>
<th>Semester</th>";
echo "<tr>";
echo "<td>";
echo $last_id;
echo "</td>";
echo "<td>";
echo $n;
echo "</td>";
echo "<td>";
echo $f;
echo "</td>";
echo "<td>";
echo $s;
echo "</td>";
echo "<br>";
}
?>
<html>
<head></head>
<body>
<form name="f1" action="" method="POST">
RollNo:
<input type="text" name="txtroll" readonly> Name:
<input type="text" name="txtname"> Faculty:
<input type="text" name="txtfac"> Semester:
<input type="text" name="txtsem">
<input type="submit" value="done" name="subbtn">
</form>
</body>
</html>

You need get $last_id after INSERT query
$sql="insert into admission_form(name,faculty,semester)values ...
mysqli_query($con,$sql);
$last_id = mysqli_insert_id($con);

You have misplaced insert query. Change it as:
<?php
$con=mysqli_connect("localhost","root","")or die("conection error");
mysqli_select_db($con,"hamdard university")or die("dbase error");
if(isset($_POST['subbtn']))
{
$sql="insert into admission_form(name,faculty,semester)values ('$n','$f','$s')";
if (mysqli_query($con, $sql))
{
$last_id = mysqli_insert_id($con);
}
$n=$_POST['txtname'];
$f=$_POST['txtfac'];
$s=$_POST['txtsem'];
$r="SELECT RollNo FROM admission_form";
$result=mysqli_query($con, $r);
echo "<table border=1>
<th>RollNo</th>
<th>Name</th>
<th>Faculty</th>
<th>Semester</th>";
echo "<tr>";
echo "<td>";
echo $last_id;
echo "</td>";
echo "<td>";
echo $n;
echo "</td>";
echo "<td>";
echo $f;
echo "</td>";
echo "<td>";
echo $s;
echo "</td>";
echo "<br>";
}
?>
<html>
<head></head>
<body>
<form name="f1" action="" method="POST">
RollNo:<input type="text" name="txtroll" readonly>
Name:<input type="text" name="txtname">
Faculty:<input type="text" name="txtfac">
Semester:<input type="text" name="txtsem">
<input type="submit" value="done" name="subbtn">
</form>
</body>
</html>

You have some problems in this page.
As stated before, the INSER query must be before the select.
If you do "SELECT RollNo FROM admission_form" you will get ALL existing RollNo in admission_form and not the lastest one. If this is an int with auto increment (that seams to be) you should do "SELECT max(RollNo) FROM admission_form".
You don't need to do the above select, as mysqli_insert_id get the ID inserted in the last query.
You might not see the result in your table because it is on HTML head, but it should be in the body of the page.
The table you create is not "closed".
You should be good to go with the code bellow.
<HTML>
<HEAD></HEAD>
<BODY>
<?php
$con=mysqli_connect("localhost","root","")or die("conection error");
mysqli_select_db($con,"hamdard university")or die("dbase error");
if(isset($_POST['subbtn']))
{
$n=$_POST['txtname'];
$f=$_POST['txtfac'];
$s=$_POST['txtsem'];
$sql="insert into admission_form(name,faculty,semester) values ('$n','$f','$s')";
if (mysqli_query($con, $r))
{
$last_id = mysqli_insert_id($con);
}
echo "<table border=\"1\"><th>RollNo</th> <th>Name</th> <th>Faculty</th> <th>Semester</th>";
echo "<tr>";
echo "<td>";
echo $last_id;
echo "</td>";
echo "<td>";
echo $n;
echo "</td>";
echo "<td>";
echo $f;
echo "</td>";
echo "<td>";
echo $s;
echo "</td>";
echo "</tr></table>";
}
?>
<form name="f1" action="" method="POST">
RollNo:<input type="text" name="txtroll" readonly>
Name:<input type="text" name="txtname">
Faculty:<input type="text" name="txtfac">
Semester:<input type="text" name="txtsem">
<input type="submit" value="done" name="subbtn">
</form>
</body>
</html>

Try this:
$mysqli = new mysqli(SQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME);
if ($result = $mysqli->query("INSERT INTO admission_form(name, facility,semester) VALUES..) {
echo 'The ID is: '.$mysqli->insert_id;
}

Related

Stop Adding Duplicate Entries to Database PHP SQLITE

I have created a PHP form which adds to a database that I have created in PHP, however, I am trying to add a function which will stop the user from adding the same fruit into the database how would I try to do this as I have been trying to do it for a while thanks.
As you can see below the PHP script works fine by adding the variable's to the database however when it comes to implementing a check to make sure the fruit name does not match one from the database already I am struggling.
<?php
//SQLite Database test query
$db=sqlite_open("fruitshop.db");
if(isset( $_POST['fruit']) && strcmp($_POST['fruit'],"") != 0 ){ //Adds to Database
$item = sqlite_escape_string($_POST["fruit"]);
$number=$_POST['number'];
sqlite_query($db,"INSERT INTO fruit (fruit) VALUES ('$item')");
sqlite_query($db,"INSERT INTO stock (Number) VALUES ($number)");
$query = "SELECT * from stock, fruit WHERE stock.Item = fruit.id AND fruit.fruit = '$item', 'fruit' = '{$item}'";
$result=sqlite_query($db, $query);
echo "<table border=1>";
echo "<tr><th>Fruit</th><th>Qty</th>";
echo "<h2>". "Newly added Fruit"."</h2>";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC ))
{
echo "<tr>";
echo "<td>" . $row['fruit.fruit'] . "</td><td>" . $row['stock.Number'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h2>". "Show All Fruits"."</h2>";
echo "<table border=1>\n";
//NOte the use of SQLITE_ASSOC
echo "</br>\n";
$result=sqlite_query($db,"SELECT * from stock, fruit WHERE stock.Item = fruit.ID"); //Shows Databse
echo "<th>Fruit</th><th>Qty</th>\n";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC))
{
echo "<tr>\n";
echo "<td>" . $row['fruit.fruit'] . "</td>\n";
echo "<td>" . $row['stock.Number'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
sqlite_close($db);
?>
<html>
<h2> Add Fruits to Database </h2>
<form name="CheckFruit" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Fruit
<input type="text" name="fruit" />
<br>
Stock
<input type="number" name="number" />
<br>
<input type="submit" value="Submit" />
</form>
</html>
You can use my updated code. Didn't get to try the code though but it should work. Also note how I used empty instead of strcmp. That's a more elegant PHP code.
<?php
//SQLite Database test query
$db=sqlite_open("fruitshop.db");
if(isset( $_POST['fruit']) && !empty($_POST['fruit']) ){ //Adds to Database
$item = sqlite_escape_string($_POST["fruit"]);
$number = $_POST['number'];
$test = sqlite_query($db, "SELECT * FROM fruit WHERE (fruit = '$item')");
if(sqlite_num_rows($test) == 0){
sqlite_query($db,"INSERT INTO fruit (fruit) VALUES ('$item')");
sqlite_query($db,"INSERT INTO stock (Number) VALUES ($number)");
} else {
// Just in case you want this too.
// echo "This database already contains a fruit called {$_POST['fruit]'}";
}
$query = "SELECT * from stock, fruit WHERE stock.Item = fruit.id AND fruit.fruit = '$item', 'fruit' = '{$item}'";
$result=sqlite_query($db, $query);
echo "<table border=1>";
echo "<tr><th>Fruit</th><th>Qty</th>";
echo "<h2>". "Newly added Fruit"."</h2>";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC ))
{
echo "<tr>";
echo "<td>" . $row['fruit.fruit'] . "</td><td>" . $row['stock.Number'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h2>". "Show All Fruits"."</h2>";
echo "<table border=1>\n";
//NOte the use of SQLITE_ASSOC
echo "</br>\n";
$result=sqlite_query($db,"SELECT * from stock, fruit WHERE stock.Item = fruit.ID"); //Shows Databse
echo "<th>Fruit</th><th>Qty</th>\n";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC))
{
echo "<tr>\n";
echo "<td>" . $row['fruit.fruit'] . "</td>\n";
echo "<td>" . $row['stock.Number'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
sqlite_close($db);
?>
<html>
<h2> Add Fruits to Database </h2>
<form name="CheckFruit" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Fruit
<input type="text" name="fruit" />
<br>
Stock
<input type="number" name="number" />
<br>
<input type="submit" value="Submit" />
</form>
</html>
You could declare the fruit column as UNIQUE in your column schema, so the database will reject a duplicate value without further controls on your side.
If instead you want to check if the value is already present in your PHP code, you can do a query for that value and check if rows are returned. If rows are returned, a value is already present and you can handle that situation before doing your inserts
$query = "SELECT * from fruit WHERE fruit.fruit = '$item', 'fruit' = '{$item}'";
$result=sqlite_query($db, $query);
if (sqlite_num_rows($result) === 0) {
sqlite_query($db,"INSERT INTO fruit (fruit) VALUES ('$item')");
sqlite_query($db,"INSERT INTO stock (Number) VALUES ($number)");
} else {
// Value is already present
}
Note: I've never used SQLITE, so i hope the syntax is correct

i need to break the line after a reach of 10 buttons

I need to break the line after a reach of 10 buttons.
Please be specific what are the code to be used for breaking the line.
Here is the code:
<?php
session_start();
require('connection.php');
$result = mysql_query("SELECT * FROM tbCandidates ");
if($result){
}
echo "select Project to Reward for";
$_SESSION['a']="project name-->";
echo "<body><form method='post' action='part1.php' ><input type='hidden' value='abhishek' name='aa'/>";
echo "<table><tr>";
while ($row=mysql_fetch_array($result)){
echo "<td>";
echo $row["project_id"];
echo '<input type="radio" name="n1" value="';echo $row["project_id"]; echo '">'; echo"</input>";
$_SESSION['b']=$row['candidate_name'];
$_SESSION['c']=$row['candidate_position'];
$_SESSION['c']=$row['candidate_nominee'];
echo "</td>";
}
echo "</tr></table><input type='submit'/></form></body>";
If you mean by BREAKING the line is creating another row for your table then try to use the following codes:
<?php
session_start();
require('connection.php');
$result = mysql_query("SELECT * FROM tbCandidates ");
if($result){
}
echo "select Project to Reward for";
$_SESSION['a']="project name-->";
echo "<body><form method='post' action='part1.php' ><input type='hidden' value='abhishek' name='aa'/>";
echo "<table>";
$counter = 0;
while ($row=mysql_fetch_array($result)){
$counter++;
if($counter==1){
echo "<tr>";
}
echo "<td>";
echo $row["project_id"];
echo '<input type="radio" name="n1" value="';echo $row["project_id"]; echo '">'; echo"</input>";
$_SESSION['b']=$row['candidate_name'];
$_SESSION['c']=$row['candidate_position'];
$_SESSION['c']=$row['candidate_nominee'];
echo "</td>";
if($counter==10){
echo "</tr>";
$counter = 0;
}
}
echo "</table><input type='submit'/></form></body>";
Let me know if it works.

Edit sql data in php page

I need to edit my database table using submitted data.
This is the form:
mysql_query("set names 'utf8'");
$query = "SELECT * FROM sec1octa";
$result = mysql_query($query);
?>
<div align="center">
<form method="get" action="edit_data.php">
<table width="104" border="1" class="center1">
<tr>
<th width="94">first</th>
<th width="94">second</th>
<th width="94">status</th>
</tr>
<tr>
<?php
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><input type="text" name="id" value="<?php echo $row ['stu_no']; ?> " size=10></td>
<td><input type="text" name="name" value="<?php echo $row ['stu_name']; ?> " size=10></td>
<td><?php
echo '<select name="status">'; {
echo '<option value="open">'.$row['stu_status'].'</option>';
echo '<option value="close">'.prevent.'</option>';
}
echo '</select>';
?></td>
</tr>
<?php
}
}
?>
</tr>
</table>
<input type="submit" name="submit" value="done" />
</form>
The problem is in the edit_data.php page.
I can't UPDATE.
I use this code but it's not working.
require_once('../Connections/config.php');
$id= $_GET['id'];
$status= $_GET['status'];
$query= mysql_query("UPDATE `goh`.`sec1octa` SET `stu_status` = '$status'
WHERE stu_no='".$id."'") or die (mysql_error ());
if($query){echo $status ."done ";}
The reason you are only getting the last values in your edit_data.php $_GET is because you are not setting the input/select names as arrays.
<input type="text" name="id" value="some_stu_no">
is happening over and over and over and every new one overwrites the previous.
Instead, you should use:
<input type="text" name="id[]" value="some_stu_no">
This will allow you to pass multiple id's in a single form submission.
Your form:
<form method="POST" action="edit_data.php">
....
echo "<tr>";
echo "<th>id</th>";
echo "<th>name</th>";
echo "<th>status</th>";
echo "</tr>";
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td><input type=\"text\" name=\"id[]\" value=\"{$row['stu_no']}\" size=\"10\"></td>";
echo "<td>{$row['stu_name']}</td>";
echo "<td>";
echo "<select name=\"status[]\">"; // I don't like your option set up here, but I don't fully understand it either.
echo "<option value=\"open\">{$row['stu_status']}</option>";
echo "<option value=\"close\">.prevent.</option>";
echo "</select>";
echo "</td>";
echo "</tr>";
}
}
....
<input type="submit" value="Submit All">
</form>
edit_data.php
// create a mysqli connection called $db
if(isset($_POST['id'])){
$tally=0;
// build all queries for the batch
foreach($_POST['id'] as $index=>$id){
$queries[]="UPDATE `goh`.`sec1octa` SET `stu_status`='".mysqli_real_escape_string($db,$_POST['status'][$index])."' WHERE `stu_no`='".mysqli_real_escape_string($db,$id)."'";
}
// run all queries
if(mysqli_multi_query($db,implode(';',$queries)){
do{
$tally+=mysqli_affected_rows($db);
} while(mysqli_more_results($db) && mysqli_next_result($db));
}
// assess the outcome
if($error_mess=mysqli_error($db)){
echo "Syntax Error: $error_mess";
}else{
echo "$tally row",($tally!=1?"s":"")," updated";
}
mysqli_close($con);
}

Stop Inserting Blank data in Refreshing browser

I'm new in PHP. some one please help to stop inserting blank data when refreshing the browser. I'm trying to insert data in SQL database from a HTML form & showing them in the same page in a table.
here is my from & PHP code
Thanks in advance....
</head>
<body>
<?php
$sub = mysql_connect ("localhost", "root","");
if (!$sub)
{
die('Could Not Connect:'.mysql_erro());
}
mysql_select_db("test", $sub);
$sql="INSERT INTO te(Dat,Sadi,Jam,Washi) VALUES('$_POST[Dat]','$_POST[Sadi]','$_POST[Jam]','$_POST[Washi]')";
if (!mysql_query($sql, $sub))
{
die('Error:'.mysql_error());
}
echo 'One Record added';
$result=mysql_query("SELECT * FROM te");
echo "<table border='1'>;
<tr>
<th>Date</th>
<th>Sadi</th>
<th>Jam</th>
<th>Washi</th>
</tr>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" .$row['Dat']."</td>";
echo "<td>" .$row['Sadi']."</td>";
echo "<td>" .$row['Jam']."</td>";
echo "<td>" .$row['Washi']."</td>";
echo "</tr>";
}
echo "</table>";
Mysql_close($sub);
?>
</body>
<form action="index.php" method="post">
<input type="text" name="Dat" placeholder="Date, DD-MM-YY">
<input type="text" name="Sadi" placeholder="Sadi">
<input type="text" name="Jam" placeholder="Jam">
<input type="text" name="Washi" placeholder="Washi">
<input type="submit" name="sub">
</form>
Just verify if the $_POST is not empty
if(!empty($_POST))
{
$sql="INSERT INTO te(Dat,Sadi,Jam,Washi) VALUES('$_POST[Dat]','$_POST[Sadi]','$_POST[Jam]','$_POST[Washi]')";
if (!mysql_query($sql, $sub))
{
die('Error:'.mysql_error());
}
}

PHP Insert table into database

I have a database table that I created from a .csv file. I used php to edit the content to match a new table on my database. I now need to INSERT that new table into the new database. I added form tags around the table and a submit button, and when I submit it I only get 1 or 2 random rows of the table. I am guessing that I might need a while or a for loop, but I cant figure out how to write it. Any assistance would be appreciated.
This is the code to post to the db
if(isset($_POST['submit'])){
$mr = $_POST['mr'];
$mrs = $_POST['mrs'];
$last_name = $_POST['last_name'];
$marital_status = $_POST['marital_status'];
$query = "INSERT INTO import_template(first_name, last_name, marital_status) VALUES('{$mr}', '{$last_name}', '{$marital_status}')";
$result = mysqli_query($connection, $query);
if(!$result){
die("QUERY FAILED " . mysqli_error($connection));
}
if(!$connection){
echo "We are NOT connected";
}
$query = "INSERT INTO import_template(first_name, last_name, marital_status) VALUES('{$mrs}', '{$last_name}', '{$marital_status}')";
$result = mysqli_query($connection, $query);
if(!$result){
die("QUERY FAILED " . mysqli_error($connection));
}
if(!$connection){
echo "We are NOT connected";
}
}
This is what the dynamic table looks like I only added the input to the first few to test, I haven't done the rest yet.
echo "<tr>";
echo "<td><input type='text' class='form-control' name='mr' value='$mr'></td>";
echo "<td><input type='text' class='form-control' name='last_name' value='$last_name'></td>";
echo "<td><input type='text' class='form-control' name='marital_status' value='$marital_status'></td>";
echo "<td>{$birthday}</td>";
echo "<td>Adult</td>";
echo "<td>{$anniversary}</td>";
echo "<td>{$mr_cell_phone}</td>";
echo "<td>{$home_phone}</td>";
echo "<td>{$mr_email}</td>";
echo "<td>{$street}</td>";
echo "<td>{$city}</td>";
echo "<td>{$state}</td>";
echo "<td>{$zip}</td>";
echo "<td></td>";
echo "</tr>";
echo "<tr>";
echo "<td><input type='text' class='form-control' name='mrs' value='$mrs'></td>";
echo "<td><input type='text' class='form-control' name='last_name' value='$last_name'></td>";
echo "<td><input type='text' class='form-control' name='marital_status' value='$marital_status'></td>";
echo "<td></td>";
echo "<td>Adult</td>";
echo "<td>{$anniversary}</td>";
echo "<td>{$mrs_cell_phone}</td>";
echo "<td></td>";
echo "<td>{$mrs_email}</td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "</tr>";
You can do like this. I have taken three fields such as task,agent and note.You can add as per your table rows:
main.php
<form id="first" action="insert_values.php" method="post">
<table>
<tr>
<td>Task</td>
<td>
<input type="text" name="task">
</td>
</tr>
<tr>
<td>Agent</td>
<td>
<input type="text" name="agent">
</td>
</tr>
<tr>
<td>Note</td>
<td><input type="text" name="Note"></td>
</tr>
</table>
<input type="submit" value="save" name="save">
</form>
insert_values.php
<?php
error_reporting( error_reporting() & ~E_NOTICE );
session_start();
include 'connect.php';
$task=$_POST['task'];
$agent=$_POST['agent'];
$Note=$_POST['Note'];
$result=mysql_query("insert into table_name(task,agent,t_note) values('$task','$agent','$Note')");
if($result)
{
$msg="Insert Successfully!!";
echo "<script>alert('Insert Successfully');document.location='main.php'</script>";
?>
<?php
}
else
{
$errmsg=" Insert not success!!";
echo "<script>alert('Insert Not Successfully');document.location='main.php'</script>";
}
?>

Categories