Stop Adding Duplicate Entries to Database PHP SQLITE - php

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

Related

PHP MySQL Get material and quantity for an order form

I need to create an order form that has a checkbox for each product in a table and have a quantity box next to each product.
I need to process the products that have been checked and update an orders table with the checked products and the quantity entered.
I don't know how to link the product checkbox to the quantity field.
$sql="select * from tproducts";
$result=mysqli_query($con, $sql) or die(mysqli_error($con));
echo "<table>";
echo "<tr>";
echo "<th>Product Names</th>";
echo "</tr>";
if(mysqli_num_rows($result)>0)
{
echo "<form action=welcome1.php method=post>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" value="' . $row['intProductID'] . '" name="materialcode[]">' . $row['strProductName'] . "</td>";
echo "<td>Enter Quantity </td>";
echo "<td><input type='text' name='qty[]' value='qty' size=5></td>";
echo "</tr>";
}
}
echo "</table>";
echo '<input type="submit" name="submit" value="submit" />';
echo "</form>";
echo "</html>";
welcome1.php
<?php
echo "materialcode<br>";
print_r($_POST['materialcode']);
echo "<br>";
echo "qty<br>";
print_r($_POST['qty']);
?>
PHP will keep the key name you supply in the fields html.
$productIndex = 0;
while ($row = mysqli_fetch_array($result) )
{
echo "<tr>";
echo '<td><input type="checkbox" value="' . $row['intProductID'] . '" name="materialcode[$productIndex]">' . $row['strProductName'] . "</td>";
echo "<td>Enter Quantity </td>";
echo "<td><input type='text' name='qty[$productIndex]' value='qty' size=5></td>";
echo "</tr>";
$productIndex++;
}
This example uses numeric indexes but you could probably use $row['intProductId'] as well.
In your php:
$_POST['materialCode'][0] will be the analog to $_POST['qty'][0] but only the checked checkboxes will be supplied. You might end up with a $_POST['materialCode'] array that has index 0, 5, and 7 if those were the only ones checked.
So use a foreach loop instead of a for loop.
foreach( $_POST['materialCode'] as $key => $value ){
$productId = $value;
$quantity = $_POST['qty'][$key];
}

how to display auto increment data form mysql in 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;
}

Change table content using a link

I am new to PHP and I made a simple program where you can apply your name and age, it will take the data to the database and the table will be added with a new row.
I want to add a new column where you can click "change", only the data from that particular row will show up in a few textboxes and can be changed. when pressing submit I want to use the UPDATE function to update the records.
example/plot:
Mike Towards 23 Change
Tyler Frankenstein 24
Change Sophie Baker 22
Change
I want to change the age of Sophie Baker to 24 so I press Change on that row.
Now I only want to get the data from that row and make some changes.
The code I have this far:
Drawing the table above the input fields and the input:
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="insert.php" method="post"><br />
<input type="text" name="firstname"> Firstname <br />
<input type="text" name="lastname"> Lastname <br />
<input type="text" name="age"> Age
<p><input type="submit"></p>
</form>
</body>
</html>
Parser:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
mysqli_close($con);
?>
I have tried a few things, but I cant figure out how to show the content on the row I want to select.
Change the actual data with the update function won't be the problem, so I only need help to get the actual data from the correct row.
you'd need to select with the primary key of that table if any exists. if not you should create one. I assume you have a primary key named PersonID:
$query = "SELECT * FROM Persons WHERE PersonID = '" . ($_GET['PersonID']) . "'";
to add the edit button:
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th><th>Action</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href = '?PersonID=" . $row['PersonID'] . "'>Edit</a></td>";
echo "</tr>";
}
echo "</table>";
I assume you have a column named "id".
you can do the following:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// when you are in "edit mode" just display the row you will edit row
if (isset($_GET['id'])
$result = mysqli_query($con,"SELECT * FROM Persons where id = ".(int)$_GET['id']);
else
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href='?id=" . $row['id'] . "'>change</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="update.php" method="post"><br />
<input type="hidden" name="id" value="<?php echo isset($_GET['id']?$_GET['id']:'') ?>" />
<input type="text" name="firstname" value="<?php echo isset($row['FirstName'])?$row['FirstName']:'' ?>"/> Firstname <br />
<input type="text" name="lastname" value="<?php echo isset($row['LastName'])?$row['LastName']:'' ?>"/> Lastname <br />
<input type="text" name="age" value="<?php echo isset($row['Age'])?$row['Age']:'' ?>"/> Age
<p><input type="submit"></p>
</form>
</body>
</html>
update.php (handle both insertion and update):
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['id'])
$sql="UPDATE Persons set FirstName = ?, LastName = ?, Age = ?
WHERE id = ".(int)$_POST['id'];
else
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)";
$sth = mysqli_prepare($con, $sql);
$sth->bind_param($_POST[firstname],$_POST[lastname],$_POST[age]);
if (!$sth->execute())
{
die('Error: ' . mysqli_error($con));
}
echo "1 record ".(isset($_POST['id']?'modified':'added')." to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";

Change Button depending on mysql_fetch_array result?

I've been doing some work on my website control panel for a game I'm working on. But I can't seem to get the "Ban!" button to be "Unban!" if the result $row['banned'] is FALSE. I get it to output TRUE : FALSE depending on what it says in the table.
Any help getting this fixed would be greatly appreciated. I have struggled with this for a few days now and I felt like giving up once or twice but this has to be completed to help the admins on my game have it easier to check banned accounts and control the options.
p.s "connect.php" only has a few variables that are used and the mysql connect string.
<?php
require('connect.php');
if(isset($_POST['ban'])){
$id = $_POST['ban_rec_id'];
$query = "UPDATE accounts SET banned=1 WHERE id=$id";
$result = mysql_query($query);
}else if(isset($_POST['unban'])){
$id = $_POST['unban_rec_id'];
$query = "UPDATE accounts SET banned=0 WHERE id=$id";
$result = mysql_query($query);
}
$query = "SELECT id, uuid, name, REPLACE(REPLACE(banned,'0','FALSE'),'1','TRUE') AS banned FROM accounts ORDER BY id ASC";
$result = mysql_query($query);
echo "<center>
<table>
<tr>
<th>Acccount Id</th>
<th>Username</th>
<th>In-Game Name</th>
<th>Banned</th>";
if($ban === true){
echo "<th>Ban</th>";
}
echo "</tr>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$username = $row['uuid'];
$gamename = $row['name'];
$banned = $row['banned'];
echo "<tr>";
echo "<td>" . $id . "</td>";
echo "<td>" . $username . "</td>";
echo "<td>" . $gamename . "</td>";
echo "<td>" . $banned . "</td>";
if($ban === true){
if($row['banned'] == FALSE){
echo "<td>"?>
<form id="ban" method="post" action="">
<input type="hidden" name="ban_rec_id" value="<?php print $id; ?>"/>
<input class="button-small" type="submit" name="ban" value="Ban!"/>
</form>
<?php "</td>";
} else {
echo "<td>"?>
<form id="unban" method="post" action="">
<input type="hidden" name="unban_rec_id" value="<?php print $id; ?>"/>
<input class="button-small" type="submit" name="unban" value="Unban!"/>
</form>
<?php "</td>";
}
}
echo "</tr>";
}
echo "</table></center>";
mysql_close($link);
?>
Try use string for FALSE instead since looks like you might have assigned it with String rather than Boolean value in your error-prone REPLACE(REPLACE(banned,'0','FALSE'),'1','TRUE'):
if($row['banned'] == 'FALSE')
So what actually is the problem with that? The code seems to be fine, in case the value in 'banned' column is false or true.
But you should check the right value type in your columns. If it is string (varchar, text etc) that is saying 'FALSE' or 'TRUE' you should use
'FALSE' instead of FALSE

Deleting multiple rows from mysql with checkbox?

I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)

Categories