Comparing user input data to mysql db - php

so i've recently got a job at a market, and they got a lot of PLU's that i need to know. So for helping me, i'm trying to do something to help me.
I've created a database with some of the items that look like this:
id art img plu_code
and in my index.php, after connecting to database and selecting a random id to show
$query = "SELECT * FROM produto ORDER BY RAND() LIMIT 1";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$imagem_produto = $row["imagem"];
$nome_produto = $row["artigo"];
$plu_produto = $row["plu"];
echo '<center><tr>
<td><img height="150" width="150" src="'.$imagem_produto.'"></td><br>
<td>'.$nome_produto.'</td><br>
<td>'.$plu_produto.'</td>
</tr></center>';
}
$result->free();
if ($plu_produto === $_GET['U']) {
echo "Correct. Please wait!";
header("Refresh:3");
}else{
echo 'Wrong.';
}
}
?>
<html>
<body>
<form method="post">
<input type="text" name="U"/>
<input type="submit" />
</form>
</body>
</html>
How do i compare the user input to the db and then show if it's correct or wrong? Thank you!

It is not like comparing the user input to the db.
Your code
if ($_POST['U'] === $plu_produto) {
compares with the last row read by the while loop which is not as expected.
After connecting to the database, have code to show all data which will show up in the first run. And after the user input you should select the relevant rows from the database itself which matches with "U" where there should not be any while loop but the sql select itself should return only one row.

You should just query for the specific PLU, not the entire table.
You also need to use $_POST, not $_GET, since the form has method="POST".
if (isset($_POST['U'])) {
$plu_produto = $_POST['U'];
$stmt = $mysql->prepare("SELECT 1 FROM produto WHERE plu = ?");
$stmt->bind_param("s", $plu_produto);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo "Correct. Please wait!";
header("Refresh:3");
}else{
echo 'Wrong.';
}
exit;
}

Related

Mysql Keeps deleting the written ID but the ID Doesn't exist in Database

I have created a HTML form where you can delete the staff just by putting the ID which is directly connected to the database.
When I put the ID first time it will delete it if its existing but even if it doesnt exist it will still say that it just got deleted even though it was never there.
Here's the PHP part of it
<?php
if(isset($_POST['removeemployees']))
{
$error = "";
if(!isset($_POST['employeeID']))
{
$employeeID = "";
}
else
{
$employeeID = $_POST['employeeID'];
}
if(empty($employeeID))
{
// Empty Employee
$error .= "employeeID Cannot be Empty";
}
//echo "Your Firstname is : $firstname and last name is : $lastname";
if($error == "")
{
$sql = "DELETE FROM employees WHERE ID = $employeeID ";
$result = mysqli_query($con, $sql);
if(mysqli_affected_rows($result) > 1)
{
echo "Record Deleted";
}
else
{
echo "Error Deleting record:".mysqli_error($con);
}
}
else
{
echo $error;
}
}
?>
And here's the HTML part of it, which is simple and working okay.
<div class="removeemployee">
<h3> Remove Employees </h3>
<p>Employee ID</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="text" name="employeeID"><br>
<br><input type="submit" name="removeemployees" value="Submit Information">
</form>
</div>
I' m trying to make it work like this: if the ID is existing you can delete it, if it's not existing it should say that this ID is not existing in database or something like that. At first I thought I have to collect all the data from Mysql then compare it with input ID and go from there but I'm not sure.
No rows to delete is not an error.
If there's an error, mysqli_execute() returns false, not a result object.
mysqli_execute() only returns a result object when the query is SELECT (or some other type that returns a result set); for modification queries it just returns true or false. The argument to mysqli_affected_rows() must be the connection, not the return value.
$sql = "DELETE FROM employees WHERE ID = ?";
$stmt = mysqli_prepare($con, $sql);
$stmt->bind_param("i", $employeeID);
$stmt->execute();
if(mysqli_affected_rows($con) > 1)
{
echo "Record Deleted";
}
else
{
echo "Employee ID does not exist";
}
I've also shown how to recode using a prepared statement to prevent SQL injection.

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

update checkboxes after submit

I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)

Multiple checkboxes inserting improperly

I've researched this for two days and just about have it working... trouble is, when I check TWO checkboxes on my dynamically populated form, I get FOUR records inserted. It gets weirder... ONE of the records is unique. THREE have the same information. I'm totally lost here.
Here is the code for the form:
<form name="form1" id="form1" method="post" action="insert_zip_codes.php?u=<?php echo $_SESSION['username'] ?>">
<table class="bordered" cellspacing="0">
<tr><th>City</th><th>State</th><th>ZIP Code</th></tr>
<?php while($row = mysql_fetch_array($rs)) { ?>
<tr><td><input name="zip_code[]" type="checkbox" id="zip_code" value="<?php echo $row[zip_code] ?>" /></td><td><?php echo $row[city] ?></td><td><?php echo $row[state] ?></td><td><?php echo $row[zip_code]?></td></tr>
<?php } ?>
</table><br />
<input type="submit" name="Submit" value="Submit" />
</form>
Here is the code for the insert statement on the next page.
<?php $u = $_GET['u']; ?>
<?php var_dump($_REQUEST); ?> </br> </br>`
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query);
}
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); ?>
When I hit submit, the following prints out and it inserts successfully into the database.
["zip_code"]=> array(2) { [0]=> string(5) "97477" [1]=> string(5) "97478" }
Looks right, right? But then the database gets these records...
id 40 username *** zip_code 97478
id 41 username *** zip_code 97478
id 42 username *** zip_code 97478
id 43 username *** zip_code 97477
As you can see, the darned thing is entering the first zipcode checked on the page only once (as the fourth record) but is entering the SECOND zipcode first THREE TIMES.
Any idea why? I'm at a loss.
Thank you in advance!!! :)
You are calling mysql_query() 3 times, and with 2 of them outside your foreach() loop, it will insert the last $query/$zip_code an additional 2 times.
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query); // 1st time (does query foreach zip_code)
}
if(mysql_query($query)) // 2nd time (does query on last zip_code a second time)
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); // 3rd time (does query on last zip_code a third time) ?>
Removing the last one, as it is just there for de-bugging, you could change your loop code to -
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
$result = mysql_query($query);
if($result)
{
echo 'success ';
}
else
{
echo 'failure' .mysql_error();
}
}
The problem relates to your use of mysql_query() and the $query variable you are using.
Here's a walk through.
You submit two postcodes via $_POST
You loop through the $_POST array and set $query to be the INSERT string.
You then pass that into the function mysql_query() to execute the command to INSERT the record.
So now, you've got two records in your database. You didn't do any checks to see if they worked individually as inserts during that loop (you should have). You also didn't do any escaping to avoid dodgy injection tampering. (you should have).
Anyway, after your loop, this is where it all goes wrong. You then check to see if it worked by running mysql_query($query) again. This is actually going to run the last $query INSERT string you generated again as a command. So that inserts another record into the table.
THEN, you do something with the variable $results by yet again, running the mysql_query($query) command. So that's another record you've inserted.
This means you would have 4 records inserted into your table.
A suggestion
This is off the top of my head! - not tested it
$u = "Whatever";
$inserted = 0;
$fatal = Array();
foreach($_POST['zip_code'] AS $z){
if(mysql_query("INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".mysql_real_escape_string($z)."')";
$success += mysql_affected_rows();
} else {
$fatal[] = mysql_error();
}
}
echo "Inserted $success of ".count($_POST[zip_code])." records.<br />";
if(count($fatal)){
$fatal = array_unique($fatal);
echo "The following error(s) occurred:<br />";
print "<pre>";
print_r($fatal);
print "</pre>";
}
Hope that helps in some way!

wrap a mysql query in a php function and print results

I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.

Categories