PHP database delete function only works on first row of database? - php

<p><?php include 'header.php'; ?></p>
<div align="justify">
<td>Name:<input type="text" name="password" ></td> <!-- database -->
<td> Rank:<select>
<!--<option value="volvo">//Database</option>
<option value="saab">Saab</option>
-->
<?php
require ("dbfunction.php");
$con = getDbConnect();
<td> <input type="checkbox" name="vehicle" value="Bike">Group by Rank</td> <!-- database -->
<td> <input type="checkbox" name="vehicle" value="Bike">Include previous service terms</td> <!-- database -->
</div>
<p><table>
<tr>
<th>Name</th>
<th>Rank</th>
<th>Start Date</th>
<th>End Date</th>
<th>Watchkeeping</th>
<th>Active</th>
<th></th>
<th></th>
</tr> <!-- database -->
<tr> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
//echo "<div><a href=http://localhost/poshproject/crewlisting.php?crew_name={$row["crew_id"]}>";
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
echo "<td>Edit";
//echo "<td><center><button type=\"submit\" name=\"Delete\" value="' . $row['crew_id'].'"/>Delete</button></center></td>";
echo "<td>Delete";
}
?>
<!--
<td><center><button type="submit" value="Edit">Edit</button></center></td>
<td><center><button type="submit" value="Delete">Delete</button></center></td>-->
</form></tr>
</tr>
</table>
---------------------delete.php---------------------
<?php
//print_r($_GET);
include 'dbfunction.php';
$con = getDbConnect();
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqliQueryStr = "DELETE FROM `posh`.`crewlist` WHERE crew_id = ". $row['crew_id'] . "";
}
mysqli_query($con, $sqliQueryStr);
header('Location: crewlisting.php');
mysqli_close($con);
//echo "user has been deleted";
}
?>
Delete function only works on first row of database. When I delete the rows that are not the first, it deletes the first row instead. Not sure where the error is when I've tried pretty much everything.

I think you are wrong on delete.php file. Put below code in your delete.php file.
---------------------delete.php---------------------
<?php
include 'dbfunction.php';
$con = getDbConnect();
if (!mysqli_connect_errno($con)) {
$sqliQueryStr = "DELETE FROM `posh`.`crewlist` WHERE crew_id = " . $_GET['id'];
mysqli_query($con, $sqliQueryStr);
}
header('Location: crewlisting.php');
mysqli_close($con);

Change your delete query as below
$sqliQueryStr = "DELETE FROM `posh`.`crewlist` WHERE crew_id = " . $_GET['id'] . "";

Related

How to insert selected value from dropdown list into another MySQL table

I'm trying to make a dropdown list that allows users to select a parts that they need, so after selecting all they need and submit it should go to MySQL database. But after selecting submit nothing is inserting into my database.
My code and connection:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "userregistration";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo 'good connection';
?>
<form action="trying.php" method=" POST">
<table border=" 1">
<thead>
<tr>
<th>Component</th>
<th>Item Name</th>
<th>Price </th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU</td>
<td>
<?php
//Retrieving CPU table
$query = $conn->query("SELECT * FROM cpu");
echo '<select name="cpu" class="cpu" onChange = $("#cpuprice").val($(this).find("option:selected").attr("cpuprice"))>';
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option cpuprice = ' . $obj['price'] . ' cpuname=' . $obj['cpuname'] . ' >' . $obj['cpuname'] . '</option> /n';
}
echo '</select>';
?>
</td>
<td>
<output id="cpuprice" disabled value="">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>GPU</td>
<td>
<?php
//Retrieving GPU table
$query = $conn->query("SELECT * FROM gpu");
echo '<select name="gpu" class ="gpu" onChange = $("#gpuprice").val($(this).find("option:selected").attr("gpuprice"))>';
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option gpuprice = "' . $obj['price'] . '" gpuname = "' . $obj['gpuname'] . '">' . $obj['gpuname'] . '</option>';
}
echo '</select>';
?>
</td>
<td>
<output class="form-control prc" id="gpuprice" disabled value="">
</td>
</tr>
</tbody>
</table>
<input class="submit" type="submit" />
</form>
I tried this but it doesn't work, after cliking submit it echo adding error and nothing inserted into my database
<?php
if (!empty($_POST["cpu"]) && !empty($_POST["gpu"])) {
$cpu = isset($_POST["cpu"]);
$gpu = isset($_POST["gpu"]);
$qstr = "INSERT INTO trycombuild(cpuname, gpuname) VALUES ('$cpu' , '$gpu')";
$query = mysqli_query($conn, $qstr);
} else
echo 'adding error';
?>
I tried to echo the $cpu and $gpu and it says undefined variable
I also tried this:
if (!empty($_POST['cpu']) && !empty($_POST['gpu'])) {
$cpu = $_POST['cpu'];
$gpu = $_POST['gpu'];
$qstr = $conn->prepare("INSERT INTO trycombuild (cpuname, gpuname) VALUES (?, ?)");
$qstr->bind_param("ss", $cpu, $gpu);
$qstr->execute();
$sqtr->close();
}
Your html is not correct. remove unnecessary space and try
<tbody>
<tr>
<td>CPU</td>
<td>
<?php
//Retrieving CPU table
$query = $conn->query("SELECT * FROM cpu");
echo '<select name="cpu" class="cpu" onChange = $("#cpuprice").val($(this).find("option:selected").attr("cpuprice"))>';
echo "<option>---select your CPU---</option>/n";
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option cpuprice = ' . $obj['price'] . ' cpuname=' . $obj['cpuname'] . ' >' . $obj['cpuname'] . '</option> /n';
}
echo '</select>';
?>
</td>
<td>
<output id="cpuprice" disabled value="">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>GPU</td>
<td>
<?php
//Retrieving GPU table
$query = $conn->query("SELECT * FROM gpu");
echo '<select name="gpu" class ="gpu" onChange = $("#tpuprice").val($(this).find("option:selected").attr("gpuprice"))>';
echo "<option>---select your GPU---</option>";
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option gpuprice = "' . $obj['price'] . '" gpuname = "' . $obj['gpuname'] . '">' . $obj['gpuname'] . '</option>';
}
echo '</select>';
?>
</td>
<td>
<output class="form-control prc" id="tpuprice" disabled value="">
</td>
</tr>
</tbody>

How to display data from database When Selecting Multiple option from Dropdown using PHP Mysqli

Script Page is working nicely. When I select the multiple options in next dashboard page, no records display. Please fix this problem. I think the selected value cannot recognize in dashboard page
Script.php
<?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
<strong>Choose Script Name : </strong><select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
<?php
$result = $conn->query("select script_name from script_details ORDER BY script_name");
while ($row = $result->fetch_assoc()) {
unset($script_name);
$script_name = $row['script_name'];
echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
}
?>
</select>
<input type="submit" name="submit" id="button" value="View Dashboard" />
</form>
Dashboard.php
<table border="1">
<tr align="center">
<th>Number </th> <th>Script Name</th> <th> Date</th>
</tr>
<?php
include("connection.php");
$select = $_POST['script'];
$selects = "SELECT * FROM script_details where script_name='$select'";
$result = $conn->query($selects);
echo "<table>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["script_name"] . "</td></tr>" . "</td><td>" . $row["date"] . "</td></tr>";
}
echo "</table>";
[This is script page Image. Selecting option from script_details database. Field name : script_name.][1]?>
This is Dashboard page. when selecting script2, script3 option. Doesnot show record for selected items.
Firstof all your code is sql vulnerable
In Scrip you didn't define values of options in <select> tag. define value first and for this you need to fetch is from database
Script.php
<?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
<strong>Choose Script Name : </strong>
<select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
<?php
$result = $conn->query("select id, script_name from script_details ORDER BY script_name");
while ($row = $result->fetch_assoc()) {
unset($script_name);
$script_name = $row['script_name'];
$id = $row['id'];
echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
}
?>
</select>
<input type="submit" name="submit" id="button" value="View Dashboard" />
</form>
In dashboard do proper markup
Dashboard.php
<table border="1">
<tr align="center">
<th>Number </th> <th>Script Name</th> <th> Date</th>
</tr>
<?php
include("connection.php");
$select = $_POST['script'];
$ids = "'" . implode("','", $select) . "'";
$selects = "SELECT * FROM script_details WHERE id IN ($ids)";
$result = $conn->query($selects);
while ($row = $result->fetch_assoc()) {
echo "<tr>"
. "<td>" . $row["id"] . "</td>"
. "<td>" . $row["script_name"] . "</td>"
. "<td>" . $row["date"] . "</td>"
. "</tr>";
}
?>
</table>
I would approach it in the following way:
$scriptsArr = $_POST['script'];
$scriptsStr = implode(',', $scriptsArr);
$selects = "SELECT * FROM script_details where script_name IN ($scriptsStr)";
I've split it to few variables so you can understand the process.
Hope I could help!
I hope your understand is not safe at all, I would suggest you will read a bit more about prepared statements:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Updating a mysqli table with a php form

I am trying to update the rank column in the users table in my database by presenting data in a PHP form and using a button to submit. However once i edit the data in my PHP form and press submit, the data in the database remains unchanged. I'm adding a (link to the) picture of the webpage, and the code is posted below.
Webpage image
<!DOCTYPE HTML>
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
Displays all data from 'users' table
*/
// connect to the database
include('../db/connect.php');
// get results from database
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Username</th> <th>Email</th> <th>Rank</th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = $result->fetch_array()) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['user_id'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td><input type="hidden" name="user_id[]" id="newrank" width="20px" min="0" max="100" value="' . $row['user_id'] . '"></td>';
echo '<td><form method="POST" action=""><input type="number" name="newrank[]" id="newrank" width="20px" min="0" max="100" value="' . $row['rank'] . '"></form></td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
if(isset($_POST['btn-update'])) {
for($i = 0; count($_POST["user_id"]); $i++) {
$_POST['newrank'][$i] = $MySQLi_CON->real_escape_string($_POST['newrank'][$i]); # If this function exists either, if not comment or remove this line!
$_POST['user_id'][$i] = $MySQLi_CON->real_escape_string($_POST['user_id'][$i]); # If this function exists either, if not comment or remove this line!
$MySQLi_CON->query('UPDATE users SET rank=' . $_POST['newrank'][$i] . ' WHERE user_id=' . $row['user_id'][$i] . '');
}
echo "Updated the rows.";
}
?>
<br>
<button type="submit" class="btn btn-default" name="btn-update" id="btn-update">Update</button></a>
<p>Add a new record</p>
</body>
</html>
Seems there is an error in your query statement
Modify this : if ($$MySQLi_CON->query($sql) === TRUE) {
with if ($MySQLi_CON->query($sql) === TRUE) {
You need to parse the id you wish to modify to the $_POST. Also, you need to use <form action="" method="POST"> in your code.
Didn't tested it, but the following should work:
<!DOCTYPE HTML>
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border='1' cellpadding='10'>
<thead> <th>ID</th> <th>Username</th> <th>Email</th> <th>Rank</th> <th colspan="3"></th></thead>
<tbody>
<?php
//Displays all data from 'users' table
// connect to the database
include('../db/connect.php');
// get results from database
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
// loop through results of database query, displaying them in the table
while($row = $result->fetch_assoc()) {
// echo out the contents of each row into a table
?>
<form action="" method="POST">
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['email'];?></td>
<td><input type="number" name="newrank" id="newrank" value="<?php echo $row['rank']; ?>"></td>
<td><input type="hidden" name="id" value="<?php echo $row['user_id']; ?>"><button type="submit" class="btn btn-default" name="btn-update" id="btn-update">Update</button></td>
<td>Delete</td>
</tr>
</form>
<?php
}
?>
</tbody>
</table>
<?php
if(isset($_POST['btn-update']))
{
$sql = 'UPDATE users SET rank=' . $_POST['newrank'] . ' WHERE user_id=' . $_GET['id'] . '';
if ($MySQLi_CON->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $MySQLi_CON->error;
}
}
?>
<p>Add a new record</p>
</body>
</html>

Get value in hidden field, and display it in another page. What's wrong with my code?

This is a table of students' ID numbers, with a button after each ID.
When I click on a button, I want it to open a new page called "score.php", and display the selected ID.
But the code doesn't work. It only show the text "ID", but not the number.
Here is "index.php"
<html>
<head>test</head>
<body>
<form method="post" action="score.php">
<?php
$result = mysql_query("SELECT * FROM term3_2556")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Student ID</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['student_id'] . '<input type="hidden" name="student_id" value=" ' . $_POST['student_id'] . ' " /> <button type="submit" name="btn_student_id" >Select</button> </td> ';
echo '</tr>';
}
echo "</table>";
?>
</form>
</body>
</html>
And here is "score.php"
<head>test</head>
<body>
<?php
$student_id = $_POST["student_id"];
echo '<p> ID: '.$student_id.'</p>';
?>
</body>
Since you are using a <button>, there is no need to use a <input type="hidden">. Just add the student_id as the button value -
<button type="submit" name="btn_student_id" value=" ' . $row['student_id'] . ' " >Select</button>
Then in you php just get the value from the clicked on button -
<?php
$student_id = $_POST["btn_student_id"];
echo '<p> ID: '.$student_id.'</p>';
?>
your index.php file will be:
<html>
<head>test</head>
<body>
<form method="post" action="score.php">
<?php
$result = mysql_query("SELECT * FROM term3_2556")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Student ID</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['student_id'] . '<input type="hidden" name="student_id" value=" ' . $row['student_id'] . ' " /> <button type="submit" name="btn_student_id" >Select</button> </td> ';
echo '</tr>';
}
echo "</table>";
?>
</form>
</body>
</html>

function unable to call WHERE id = $id

I'm trying to do a multiple edit function, the code goes through but the database is not updated. I figure the problem is that at WHERE id = $id no value gets called out because if I replace $id with an actual id e.g. id = 001 the entry 001 gets updated.
This page selects which entries get edited
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " . "FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (date("Y-m-d") > $row['start_date'] && date("Y-m-d") < $row['end_date']) {
echo "<tr><th>" . "<input type = 'checkbox' name = 'checkbox2[]' value='" . $row['crew_name']. "' >" . "</th>";
echo "<th>" . "" . $row["crew_name"] . "";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
} else {
}
}
?>
This is the edit page
<?php include 'header.php'; ?>
<div id="container4"><?php
require ("dbfunction.php");
$con = getDbConnect();
$checkbox2 = $_POST['checkbox2'];
if (!mysqli_connect_errno($con)) {
$str = implode($checkbox2);
$queryStr = "SELECT * " .
"FROM crewlist WHERE ($str) && crew_id";
}
$result = mysqli_query($con, $queryStr);
?><form action="handlemultiedit.php" method="post"><?php
if ($_POST['submit']) {
$checkbox2 = $_POST['checkbox2'];
foreach ($checkbox2 as $crewname) {
?>
<input type="hidden" name="crew_id" value="<?php $id = isset($_GET['id']) ? $_GET['id'] : ''; ?>" />
<?php echo "<tr><th>" . $crewname . ":</th><br>";
echo " <tr>
<td>Shift 1:</td>
<td><input type=\"time\" name=\"start_hour\" value=\"start_hour\" id=\"start_hour\" step=\"1800\" required> to <input type=\"time\" name=\"end_hour\" value=\"end_hour\" id=\"end_hour\" step=\"1800\" required>
</td>
</tr>
<tr>
<td>Shift 2:</td>
<td><input type=\"time\" name=\"start_hour2\" value=\"start_hour2\" id=\"start_hour2\" step=\"1800\" required> to <input type=\"time\" name=\"end_hour2\" value=\"end_hour2\" id=\"end_hour2\" step=\"1800\" required>
</td>
</tr><br><br>";
?><?php
}?><td><input type="submit" value="Submit" ></td></form><?php
}
?>
print_r($_POST);
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$start_hour = $_POST["start_hour"];
$end_hour = $_POST["end_hour"];
$start_hour2 = $_POST["start_hour2"];
$end_hour2 = $_POST["end_hour2"];
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET start_hour = '$start_hour',end_hour = '$end_hour', start_hour2 = '$start_hour2',end_hour2 = '$end_hour2' WHERE crew_id = $crew_id";
mysqli_query($con, $sqlQueryStr);
}
//header('Location: crewlisting.php');
mysqli_close($con);
?>
Try placing single quotes (i.e. 's) around your final variable in your statement, as you have done with all of your other variables, i.e. change it to "WHERE crew_id = '$crew_id'";

Categories