primary key increase not orderly - php

i have a list of card names and a php file inserting card. When i inserted one card and deleted it in the database then inserted again. The primary key increase after the card delete. For example:
Card number 1
Card number 2
Card number 3 --> if i delete this value and inserte again the primary key is 4 not 3 how to fix that problem ?
Here is my code
<?php
// this file show card name and picture
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
$query="SELECT * FROM dragon ";
$result=mysqli_query($connect,$query) or die("can't execute query");
echo $_SESSION['count'];
echo "<hr/>";
while($row=mysqli_fetch_assoc($result))
{
extract($row);
echo $type."<br/>";
echo $CardName."/";
echo $Description;
echo "<br/>";
echo "<a href='../dragon/{$picture}' border='0'> <img src='../dragon/{$picture}' border='0' width='300' height='300'/></a>";
echo "<hr/>";
}
?>
this file shows the insert form
<?php
$labels=array("type"=>"type",
"CardName"=>"Card Name",
"Description"=>"Description",
"atk"=>"Attack",
"def"=>"Defend",
"picture"=>"picture");
echo "<form action='InsertCard.php' method='POST'>";
echo "<h2>Insert new card </h2>";
foreach($labels as $keys =>$values)
{
echo "$values <input type='text' name='$keys'/><br/>";
}
echo "<input type='submit' value='insert new cards'/>";
echo "<input type='submit' name='return' value='return'/>";
echo "</form>";
?>
this file handle the inserted file
<?php
$labels=array("type"=>"type",
"CardName"=>"Card Name",
"Description"=>"Description",
"atk"=>"Attack",
"def"=>"Defend",
"picture"=>"picture");
if(#isset($_POST['return']))
{
header("Location:ShowCatalog.php");
}
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die("can't connect to server");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
if($keys=='type' or $keys=='CardName' or $keys=='Description' or $keys=='picture')
{
$empty_values[]=$keys;
}
}
else
{
if($keys=='type')
{
if(!preg_match("/^[A-Za-z -]{4,15}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='CardName')
{
if(!preg_match("/^[A-Za-z -]{4,30}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='Description')
{
if(!preg_match("/^[A-Za-z., -]{4,255}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=="atk" or $keys=="def")
{
if(!preg_match("/^[0-9]{3,5}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='picture')
{
if(!preg_match("/^[A-Za-z -]{4,30}(.jpg)$/",$values))
{
$invalid_data[]=$keys;
}
}
/*else
{
$clean_data[$keys]=trim(strip_tags($values));
}*/
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_data)>0)
{
if(#sizeof($empty_values)>0)
{
$join=join(", ",$empty_values);
$msg="You forgot to input: $join<br/>";
echo $msg;
}
if(#sizeof($invalid_data)>0)
{
$join=join(", ",$invalid_data);
$msg="Invalid data: $join";
echo $msg;
}
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
echo "<h2>Insert new card </h2>";
foreach($labels as $keys =>$values)
{
echo "$values <input type='text' name='$keys'/><br/>";
}
echo "<input type='submit' value='insert new cards'/>";
echo "<input type='submit' name='return' value='return'/>";
echo "</form>";
exit();
}
foreach($_POST as $keys =>$values)
{
$queried_data[$keys]=mysqli_real_escape_string($connect,trim(strip_tags($values)));
}
$check_existence="SELECT CardName FROM dragon WHERE CardName=";
foreach($queried_data as $keys =>$values)
{
if($keys=="CardName")
{
$check_existence.="'".$values."'";
}
}
$checking_result=mysqli_query($connect,$check_existence)or die("can't execute query ".mysqli_error($connect));
if(mysqli_affected_rows($connect)>0)
{
echo "card is already existed !";
include("ShowForm.php");
exit();
}
else
{
$query="INSERT INTO dragon(";
foreach($queried_data as $keys =>$values)
{
$query.=$keys.",";
}
$query.=")";
$query=preg_replace("/\,\)/",")",$query);
$query.="VALUES(";
foreach($queried_data as $keys =>$values)
{
if($keys=="type" or $keys=="CardName" or $keys=="Description")
{
$values=ucfirst($values);
}
if($keys=="atk" or $keys=="def")
{
if(empty($values))
{
$values='n/a';
}
}
$query.="'".$values."',";
}
$query.=")";
$query=preg_replace("/\,\)/",")",$query);
$result=mysqli_query($connect,$query);
echo "card is inserted !";
}
?>

That is expected behaviour, in other words, that's now AI works. Instead of counting on the ID's being sequential, you should keep track of this by yourself in case you need it. When you have done an insert with mysqli, you can fetch the "insert id" after the query has been done, if you need it for reference later.
For more information on getting insert id see:
http://www.php.net/manual/en/mysqli.insert-id.php

This is not a problem. When using autoincrement primary keys, the key assigned to your input is the lowest positive value that has not been assigned yet. This is useful in many ways. For example, you have another table with a foreign key. If your design is bad, you may delete a row from this table and remain with an orphan foreign key. This is a easy detectable error, but if when you insert another row, it gets the key of the deleted row, then yor foreign key will point to other data. This error is very hard to detect. So, the problem is not how keys are assigned, but your expectations. You might consider asking what are you trying to achieve, in order to get an useful answer for your work.

I see you didn't post any code relating to the delete query, so if you are using a delete in sql manually use the following code.
ALTER TABLE dragon AUTO_INCREMENT = 1
this will reset auto incrementing, and sql will insert the next highest integer.
see https://stackoverflow.com/a/8923132/2401804

Related

HTML form sends the wrong database ID PHP

I made a user system for my website. If you open it you well see a list of all users and you can lock or unlock them by changing "n_gesperrt" in the database to 1 or 0. 1 means locked.
The form you see here is always sending the last user id (n_id) to the php script on the top. So if I want to change something it only works with the last user shown on the list.
How can I solve that problem?
These are the code pieces:
THE FORM:
while ($zeile = mysqli_fetch_assoc($res))
{
echo "<form name=\"nutzer_sperren\" method=\"POST\" action=\"index.php?page=nutzer_sperren\">";
echo "<input type=\"hidden\" name=\"n_id\" value=\"".$zeile['n_id']."\">";
echo $zeile['n_id'];
if($zeile['n_gesperrt'] == 0){
echo "<input type =\"submit\" name=\"sperren\" value=\"Nutzer sperren\">";
}
else {
echo "<input type =\"submit\" name=\"entsperren\" value=\"Nutzer entsperren\">";
}
echo '</form">';
THE EDITING IN DATABASE:
if(isset($_POST['sperren']))
{
$sperrung = mysqli_real_escape_string($verbinde, 1);
mysqli_query($verbinde, 'UPDATE nutzer SET n_gesperrt ="'.$sperrung.'" WHERE n_id ='.$_POST["n_id"].'') or die(mysqli_error($verbinde));
echo "Daten wurden erfolgreich geändert. <br>Bitte aktualisieren Sie die Seite!";
echo $_POST["n_id"];
echo "<hr>";
}
if(isset($_POST['entsperren']))
{
$entsperren = mysqli_real_escape_string($verbinde, 0);
mysqli_query($verbinde, 'UPDATE nutzer SET n_gesperrt ="'.$entsperren.'" WHERE n_id ='.$_POST["n_id"].'') or die(mysqli_error($verbinde));
echo "Daten wurden erfolgreich geändert. <br>Bitte aktualisieren Sie die Seite!";
echo $_POST["n_id"];
echo "<hr>";
}
There are few things you need to change in your code, such as:
... The form you see here is always sending the last user id (n_id) to the php script on the top. So if I want to change something it only works with the last user shown on the list.
That's because you've assigned the same name attribute for all of your hidden input elements. Change your name attribute in the following way,
... name='n_id[]' ...
Change the name attribute of submit elements to just submit, because in this way you don't have to use two separate if blocks to handle user's response.
Remove the double quote from echo '</form">';, otherwise your form would break.
So your while() loop should be like this:
while ($zeile = mysqli_fetch_assoc($res)){
echo "<form method='POST' action='index.php?page=nutzer_sperren'>";
echo "<input type='hidden' name='n_id[]' value='".$zeile['n_id']."'>";
if($zeile['n_gesperrt'] == 0){
echo "<input type ='submit' name='submit' value='Nutzer sperren'>";
}
else {
echo "<input type ='submit' name='submit' value='Nutzer entsperren'>";
}
echo '</form>';
}
Furthermore, as I said above, you don't have to use two separate if blocks, just use one if block to check whether the form is submitted or not and toggle the n_gesperrt column value in your UPDATE operation, like this:
if(isset($_POST['submit'])){
mysqli_query($verbinde, 'UPDATE nutzer SET n_gesperrt = IF(n_gesperrt = 1, 0, 1) WHERE n_id ='.$_POST["n_id"][0]) or die(mysqli_error($verbinde));
echo "Daten wurden erfolgreich geändert. <br>Bitte aktualisieren Sie die Seite!";
}
bro use name as array
like below and you will get your result in array
while ($zeile = mysqli_fetch_assoc($res))
{
echo "<form name=\"nutzer_sperren\" method=\"POST\" action=\"index.php?page=nutzer_sperren\">";
echo "<input type=\"hidden\" name=\"n_id[]\" value=\"".$zeile['n_id']."\">";
echo $zeile['n_id'];
if($zeile['n_gesperrt'] == 0){
echo "<input type =\"submit\" name=\"sperren[]\" value=\"Nutzer sperren\">";
}
else {
echo "<input type =\"submit\" name=\"entsperren[]\" value=\"Nutzer entsperren\">";
}
echo '</form">';
on submission page get value like
$name=$_POST['entsperren'];
print_r($name);

SESSSION still work afterclosing tabs

i create php files that check user login in. If the user and password is correct, user can visit the catalog page. However there are some problems with the session. After reopening browser it still display the hidden data. I know the session will be closed when i close the browser but this case seems weird. This is the login form:
<html>
<body>
<?php
$LabelLogin=array("login"=>"login",
"password"=>"password",
);
echo "<h1> Login and Register Page </h1>";
echo "<form action='CheckLoginDetail.php' method=POST>";
foreach($LabelLogin as $keys =>$values)
{
if($keys=='password')
{
echo "$values <input type='password' name='$keys' /><br/>";
}
else
{
echo "$values <input type='text' name='$keys' /><br/>";
}
}
echo "<input type='submit' value='submit' />";
echo "<br/>click <a href='register.php'>here<a/> to register if you don't have an accout <br/>";
echo "</form>";
?>
</body>
2nd CheckLoginDetail.php
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
$labels=array("login"=>"login",
"password"=>"password");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
$empty_values[]=$keys;
}
elseif(!preg_match("/^[A-Za-z0-9_]+$/",$values))
{
$invalid_values[]=$keys;
}
else
{
$data[$keys]=$values;
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_values)>0)
{
if(#sizeof($empty_values)>0)
{
echo "login name or password or both can not be empty !";
}
if(#sizeof($invalid_values)>0)
{
echo "values contain invalid characters";
}
include("FrontPage.php");
exit();
}
else
{
foreach($data as $keys =>$values)
{
$clean_data[$keys]=mysqli_real_escape_string($connect,strip_tags(trim($values)));
}
$query="SELECT LoginName and Password FROM yugimemberinfo WHERE LoginName='";
foreach($clean_data as $keys =>$values)
{
if($keys=="login")
{
$query.="$values'";
}
if($keys=="password")
{
$values=md5($values);
$query.=" AND Password='$values'";
}
}
$result=mysqli_query($connect,$query) or die("can't execute query ".mysqli_error($connect));
if(mysqli_num_rows($result)==0)
{
echo "login fail";
include("FrontPage.php");
exit();
}
else
{
$_SESSION['access']="yes";
echo "login succesfully !<br/>";
echo "Here are two options for you :<br/>";
echo "<ul>
<li><a href='ShowCatalog.php'>Go to Card Catalog</a></li>
<li><a href='search_form.php'>Searching for your cards</a></li>
</ul>";
$query_insert="INSERT INTO yugimember (LoginName,LoginTime) VALUES(";
foreach($clean_data as $keys =>$values)
{
//echo "$keys =>$values<br/>";
if($keys=="login")
{
$query_insert.="'$values',";
}
}
//insert login name and time to yugimember
$query_insert.="'".date("Y-m-d H:i:s")."')";
$result=mysqli_query($connect,$query_insert) or die ("can't execute query line 62");
}
}
?>
if users login successfully, they can lick to the link that take them to another site called "ShowCatalog.php"
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
if(#$_SESSION['access'] != 'yes')
{
include("FrontPage.php");
exit();
}
$query="SELECT * FROM dragon ";
$result=mysqli_query($connect,$query) or die("can't execute query");
echo "<hr/>";
while($row=mysqli_fetch_assoc($result))
{
extract($row);
echo $type."<br/>";
echo $CardName."<br/>";
echo $atk." \ ".$def."<br/>";
echo $Description;
echo "<br/>".$picture."<br/>";
echo "<br/>";
echo "<a href='../dragon/{$picture}'><img src='../dragon/{$picture}' height='300' width='300'></a>";
echo "<hr/>";
}
?>
I make the ShowCatalog.php only display data for user logining in. However when i login in and close the browser then reopen it the ShowCatalog.php the data is stilled appear.
Not sure but when you do this :
if(#$_SESSION['access'] != 'yes')
If the session does not exist (because you closed your browser), maybe it will bypass this condition.
Try :
if (!isset($_SESSION['access']) | $_SESSION['access'] != 'yes')

Issue with php/mysql inserting entry with checkbox checked into database

Below is the code from catalog page with the data which has to be inserted to the database. It has some problem and i cant insert that data to the database table, and i think i have not ported variables correctly.
My catalogue page has this code (it is for purchasing photographs):
while ($row=mysql_fetch_assoc($result))
{
echo "<tr><td width=100><img src=".$row['FilePath']." /></td>";
echo "<td width=100 padding=25>".$row['Title']."</td>"; $hour = time() + 3600; setcookie('titlecookie', $row['Title'], $hour);
echo "<td width=100 padding=25>".$row['Cost']."</td>";
echo "<td width=100>".$row['FileSize']."</td>";
echo "<td width=100>".$row['CaptureDate']."</td>";
echo "<td width=100>".$row['Resolution']."</td>";
echo "<td width=100><input type=checkbox name=checked[] value=select />Purchase</td></tr>";
}
echo "</table><input type=submit name=submit value=Purchase></form></center>";
}
else
{
echo "Query not successful";
}
The code for my purchase page appears as follows:
$username = "COOKIE['ID_my_site']";
$title = "COOKIE['titlecookie']";
$Custid = mysql_query("SELECT Custid from Customer Where Username=$username");
$Money = $_POST['Cost'];
$Photoid = mysql_query("SELECT Photoid from Photograph Where Title = $row[Title]");
foreach ($_POST['checked'] as $select) {
if(mysql_query('INSERT INTO Transaction (Money, Custid)
VALUES ($Money, $Custid)'))
{
echo "successfully added to Transaction";
}
else
{
echo "Problems adding data to Transaction";
}
if(mysql_query("INSERT INTO TransPhoto (Photoid, Transid)
VALUES ('$Photoid', '$Transid')"))
{
echo "successfully added to Transphoto";
}
else
{
echo "Problems adding data to Transphoto";
}
}
Could you possible assist me with fixing this code? I am relatively new to this but have searched and could not find an effective solution. Thanks

Deleting one row from the database using the ID

I have problems with deleting a record from the screen using MSQLI.
Here you can see the code i'm using.
<?php
include_once("assets/classes/connection.php");
include_once("assets/classes/article.class.php");
while($test = $allArticles->fetch_assoc())
{
if($test['titel']=="")
{
echo "<div class='zonderfoto'>";
echo "<h5>"."geen titel hier, aparte opmaak geslaagd" . "<br /></h1>";
echo "<p>" . $test['article'] . "</p>";
echo "<input type='submit' name='verwijderee' value='verwijder'>";
echo "</div>";
}
else
{
echo "<div class='metfoto'>";
echo "<h1>".$test['titel'] . "<br /></h1>";
echo "<p>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' name='verwijder' value='verwijder'>";
echo "</form>";
echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
}
$vArticle = new Article;
$vArticle -> Key = $test['id'];
if (isset($_POST['verwijder']))
{
$vArticle -> deleteArticle();
echo ("shit");
}
?>
I'm using a while function to print all the DB records on the screen. The if function is just a function to give some design with css so nothing more. With the delete button i want to delete the record from the screen. With the $test['id'] variabele you receive the ID of the record in the DB
Ok here is my code from the class.
public function deleteArticle()
{
include("connection.php");
$sSql = "DELETE FROM tblArticles WHERE id = '".$this->m_sKey."'";
if (!$mysqli -> query($sSql))
{
throw new Exception("Something went wrong");
}
}
EDIT
There is something wrong with the key, i replaced the where statement with title ="", so i deleted one title in the database, and when i click on delete then, he delete one row, but this is not happening at runtime. so i click delete, one row deleted, BUT the content only dissapear with a page refresh. The solution is using ajax?
public function deleteArticle()
{
include("connection.php");
$sSql = "DELETE FROM tblArticles WHERE id = '".$this->m_sKey."'";
$mysqli->query($sSql);
$aff_rows = $mysqli->affected_rows;
if ($aff_rows){
print("Affected rows (DELETE): %d\n", $aff_rows);
}
else{
print("Nothong Happend ?");
if ($err = $mysqli->error){
print("Error: %s\n", $err);
}
}
}

mysql comparing two integers from two tables

if($num>0) {
echo "<table border=2> Table Request".$_SESSION['s1'];
echo"<tr>
<td>Id</td><td>Drug</td><td>Quantity</td>
</tr>";
for($i=0;$i<$num;$i++) {
$row=mysql_fetch_row($result);
$r[$i]=$row[1];
echo "<tr>";
for($j=0;$j<$num1;$j++) {
echo"<td>$row[$j]</td>";
}
echo"<td><input type='Checkbox' name='p[$i]' value='on' unchecked /></td>";
echo"<td><input type='txt' name='q[$i]' /></td>";
echo"</tr>";
$r[$i]=$row[1];
}
if(isset($_POST['p'])) {
foreach($_POST['p'] as $key=>$value) {
if($value == "on") {
$query8 = "select $r[$i] from $_SESSION['t'] ";
echo $query8;
$result8 = mysql_query($query8);
$num8=Mysql_num_rows($result8);
if($num8!=0) {
$query7="select qun from $_SESSION['t']";
$result7 = mysql_query($query8);
//?????????????????
}
}
echo"</table>";
}
}//result
}//else
I have a table request and another table for example E.
I want to compare the field quantity of these tables
if(select qun from request)<((select qun from $_SESSION['t'])) // some work
How can I write this code in the part that I marked with many question marks?
is this correct?
If you really want what the title says, why you don't do something like that
SELECT table1.quantity AS qu1, table2.quantity AS qu2 FROM table1, table2 WHERE your_conditions;
When you get the results, you can compare qu1 against qu2.
But if you are looking for something different, than please be more specific with your question.
Actual example:
$query8 = 'SELECT '.$_SESSION[ 't'].'.'.$r[$i].' AS qu1, request.qun AS qu2 FROM '.$_SESSION[ 't'].', request';
$result8 = mysql_query($query8);
while ($row8 = mysql_fetch_array($result8)) {
if ($row8[ 'qu1'] < $row8[ 'qu2']) {
echo 'the value from '.$r[$i]. ' is smaller';
} elseif ($row8[ 'qu1'] > $row8[ 'qu2']) {
echo 'the value from '.$r[$i]. ' is bigger';
} else {
echo 'both values are same';
}
}

Categories