PHP/Mysqli: Why does this code doubles rows insert? - php

I need a help with my code; somehow my code creates two rooms (it inserts two rows into a table at once), I don't know why.
(I need to require an id for every insert to know in which house we create a new room. My database contains table 'house' and table 'room'. Table 'room' has a field 'house_id' which is a foreign key with a field 'id' in table 'house'.)
That is my php page:
<?php
// turn autocommit off
mysqli_autocommit($con, FALSE);
// fetch the houses so that we have access to their names and id
$query = "SELECT name, id
FROM house";
$result = mysqli_query($con, $query);
// check query returned a result
if ($result === false) {
echo mysqli_error($con);
} else {
$options = "";
// create an option
while ($row = mysqli_fetch_assoc($result)) {
// $options .= "".$row['name']."";
$options .= "<option value='".$row['id']."'>";
$options .= $row['name'];
$options .= "</option>";
}
}
include('templates/add_room.html');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = mysqli_real_escape_string($con, $_POST["price"]);
$house = mysqli_real_escape_string($con, $_POST["house_id"]);
$query = "INSERT INTO room (price, house_id)
VALUES ('$price', '$house')";
// run the query to insert the data
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
echo "<script type= 'text/javascript'>alert('New room created successfully with the id of {$con->insert_id}');</script>";
mysqli_commit($con);
} else {
echo "There was a problem:<br />$query<br />{$con->error}";
mysqli_rollback($con);
}
}
//free result set
mysqli_free_result($result);
?>
and that is my html template with form:
<h2>Add new room</h2>
<form action='' method='POST'>
<fieldset>
<label for='price'>Price:</label>
<input type='number' name='price'>
</fieldset>
<fieldset>
<label for='house_id'>House:</label>
<select name='house_id' required>
<option value='' disabled selected>Select house</options>
<?php echo $options; ?>
</select>
</fieldset>
<button type='submit'>Add</button>
</form>

It inserts 2 rows because of your using the query function twice:
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
So you'll need to change that conditional statement to:
if ($result) {
By the way, use a prepared statement, it's safer than real_escape_string():
https://en.wikipedia.org/wiki/Prepared_statement

You are inserting it twice
first here:
// run the query to insert the data
$result = mysqli_query($con, $query);
then here:
// check if the query went ok
if ( $con->query($query) ) {
Remove the first one and you should be fine, or check on the result of the first one and remove the second one.

Not 100% certain, but it looks like you run INSERT query twice. Once here:
$result = mysqli_query($con, $query);
and once a moment later when you try to check for something. you inadvertently use the OOP style when you are apparently trying to check for something
if ( $con->query($query) ) {

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.

mysqli insert into database from multiple checkbox with foreach

so i tried to get data from my database to checkbox and this is what i have tried :
<?php
$query = "SELECT * FROM siswa WHERE id_tingkatan='$idtingkatan'";
$result = $koneksi->query($query);
while($row=$result->fetch_assoc()){
?>
<input type="checkbox" name="murid[]" value="<?php echo $row['id_siswa']; ? >"><?php echo $row["nama_siswa"]; ?><br><br>
<?php } ?>
and save the value of checked checkbox into database, this is what i have tried :
if(isset($_POST["submit"]))
{
if(!empty ($_POST['murid']))
{
$i= 0;
foreach($_POST as $murid){
$kelas = $_POST['kelas'];
$murid = $_POST['murid'][$i];
$query = "INSERT INTO murid (id_kelas, id_siswa) VALUES ('$kelas', '$murid')";
$q = mysqli_query($koneksi, $query) or die (mysqli_error($koneksi));
$i++;
}
}
else
{
echo "<script type= 'text/javascript'>alert('Pilih minimal 1 siswa');</script>";
header('Location: ./kelas.php');
}
}
when i submit it does input to database but theres one extra row with id_siswa value as 0
The code inserts one record for each value in $_POST. However, $_POST contains all parameters sent (including submit), not just the checkbox array to be inserted. Iterate over the checkbox array $_POST['murid'] instead.
Change
foreach($_POST as $murid) ...
To
foreach($_POST['murid'] as $murid) ...

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)

PHP: Delete || Confirm delete

I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..

Issue deleting rows in SQL of type varchar

I am trying to create a form that will delete a row in a table based on the attribute a user selects from a drop down list of options. For some reason the first option, (attemptid) which is an int, works, but the other three (which are varchar) do not. The error handling I have set up to debug the script is returning 1 or true, but the row in question is not deleted.
HELP! I have tried everything but am only just learning PHP so imagine I am missing something quite simple.
require_once("settings.php");
$conn = #mysqli_connect($host, $user, $pass, $db);
if ($conn) {
?>
<form method="post" action="delete_attempts.php" name="delete_attempts" id="delete_attempts" >
<label for="deleteby">
<p>Select an option to delete results by:</p>
</label>
<select name="deleteby">
<option value="attemptid">Attempt ID</option>
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
<option value="studentid">Student ID</option>
</select>
<p></p>
<input type="text" name="delvalue" placeholder="Value">
<div>
<input type="submit" value="Delete Record" id="submit" />
</div>
</form>
<?php
if (isset($_POST["delvalue"])) {
// get value from form
$delValue = trim($_POST["delvalue"]);
echo $delValue;
// queries to delete record
$queryAttemptId = "DELETE FROM quizattempts WHERE attemptid = '$delValue'";
$queryFirstName = "DELETE FROM quizattempts WHERE firstname = '$delValue'";
$queryLastName = "DELETE FROM quizattempts WHERE lastname = '$delValue'";
$queryStudentId = "DELETE FROM quizattempts WHERE studentid = '$delValue'";
//select which value to search for
if ($_POST["deleteby"] = "attemptid") {
// pass query to database
$result = mysqli_query($conn, $queryAttemptId);
} // end delete attemptid
else if ($_POST["deleteby"] = "firstname") {
// pass query to database
$result = mysqli_query($conn, $queryFirstName);
} // end delete firstname
else if ($_POST["deleteby"] = "lastname") {
// pass query to database
$result = mysqli_query($conn, $queryLastName);
} // end delete lastname
else if ($_POST["deleteby"] = "studentid") {
// pass query to database
$result = mysqli_query($conn, $queryStudentId);
} // end delete student id
echo "this is the result $result";
// if query is successful are found
if ($result) {
echo "<p>Delete operation successful</p>";
} // end if result found
else {
// if no record is found in DB
echo "<p>No records found</p>";
} // end if no result found
} //isset($_POST["attemptid"])
} //$conn
?>
if ($_POST["deleteby"] = "attemptid") {
That should be ==. Your code as written will assign "attemptid" to $_POST["deleteby"] and then return the same value... which is always true. So your other else ifs are never even checked.
Also, your code as written is vulnerable to SQL injection. You're already using mysqli; you should strongly consider using prepared statements.

Categories