I have a problem on Deleting my records it delete records but it always delete the first record not the corresponding data that I choose.
function deleterec()
{
$server = "127.0.0.1";
$username = "root";
$password = "";
$database = "inventory";
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
$getstarteds = $conn->prepare("SELECT * FROM record");
$getstarteds->execute();
$displayrecs = $getstarteds->fetch();
if (count($displayrecs) > 0) {
$_SESSION['id'] = $displayrecs['id'];
$checkrec = $conn->prepare("INSERT INTO archive SELECT * from record where id = '" . $_SESSION['id'] . "'");
if ($checkrec->execute()) {
$sql = "DELETE FROM record WHERE id='" . $displayrecs['id'] . "'";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
echo '<script language="javascript">';
echo 'alert("Record is Deleted")';
echo '</script>';
echo "<script>setTimeout(\"location.href='main.php'\",100);</script>";
}
}
}
here is my page.
enter image description here
here is my view code
$getstarteds = $conn->prepare("SELECT * FROM record");
$getstarteds->execute();
$displayrecs = $getstarteds->fetchAll();
echo"<table class='table table responsive' id='example'>";
foreach($displayrecs as $displayrec)
{
echo"<tr>";
echo"<td>".$displayrec['eq_type']."</td>";
echo"<td>".$displayrec['eq_num']."</td>";
echo"<td>".$displayrec['model']."</td>";
echo"<td>".$displayrec['serial_num']."</td>";
echo"<td>".$displayrec['location']."</td>";
echo"<td>".date("F j, Y",strtotime($displayrec['date_added']))."</td>";
echo"<td><form action='main.php' method='POST'><button name='deletethis' class='btn btn-costume1'><i class='fa fa-times' aria-hidden='true'></i></button><a data-toggle='modal' data-target='#myEdit' class='btn btn-costume3'><i class='fa fa-pencil' aria-hidden='true'></i></a></form></td>";
echo"</tr>";
}
Your select $getstarteds = $conn->prepare("SELECT * FROM record"); without WHERE condition and this line $displayrecs = $getstarteds->fetch(); always get the first record
Related
I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer
My PHP script is returning the Mysql value with the highest ID, not the requested ID:
<?php
$db = mysqli_connect('localhost', 'root', '(Password)', 'web');
#THE 'userEmail' variable is from a script above not displayed on here
$email = $row['userEmail'];
$result = mysqli_query($db, "SELECT * FROM table WHERE email = '$email'");
echo "<center><table border='1'>
<tr>
<th>Username</th>
<th>Password</th>
<th>Active?</th>
<th>Add Account</th>
<th>Delete Account</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$userName = $row['username'];
$passWord = $row['password'];
$addId = $row['id'];
$deleteId = $row['id'];
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>" . $row['activeStatus'] . "</td>";
echo "<td><a href=home.php?add=$addId>Add Account</a></td>";
echo "<td><a href=home.php?delete=$deleteId>Delete Account</a></td>";
echo "</tr>";
}
echo "</table></center>";
if( isset($_GET['delete']) ) {
$deleteId = $_GET['delete'];
$delete = "DELETE FROM table WHERE id = $deleteId";
$result = mysqli_query($db, $delete);
deleteLineInFile("/var/www/html/table-users.txt","'$userName'");
if ($result == TRUE) {
echo "Record updated successfully";
header('Location: home.php');
} else {
echo "Error updating record";
}
}
if( isset($_GET['add']) ) {
$addId = $_GET['add'];
$add = "(Too long to display)";
echo("$userName, $passWord");
file_put_contents("/var/www/html/directory/$addId.xml", $add);
header("Location: directory/$addId.xml");
}
function deleteLineInFile($file,$string)
{
$i=0;$array=array();
$read = fopen($file, "r") or die("can't open the file");
while(!feof($read)) {
$array[$i] = fgets($read);
++$i;
}
fclose($read);
$write = fopen($file, "w") or die("can't open the file");
foreach($array as $a) {
if(!strstr($a,$string)) fwrite($write,$a);
}
fclose($write);
}
?>
Every time I try to get the ID, it only displays the id with the highest value. I don't know what the problem is. I think it is a problem with the row because the $userName = $row['username']; and $passWord = $row['password']; lines are stored in the loop. I noticed that it will pick up the id for the $_GET variable correctly, but it won't for the $row variable. Could someone help me figure out this situation?
When the form is submitted, $userName and $password don't contain the info for the submitted ID, they contain the last value from the while loop. You need to do a database query to look up the corresponding username.
if( isset($_GET['add']) ) {
$addId = $_GET['add'];
$add = "(Too long to display)";
$stmt = mysqli_prepare($db, "SELECT username, password FROM table WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $addId);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $userName, $passWord);
if (mysqli_stmt_fetch($stmt)) {
echo("$userName, $passWord");
file_put_contents("/var/www/html/directory/$addId.xml", $add);
header("Location: directory/$addId.xml");
} else {
die("User ID $addId not found");
}
}
I've also shown how to use a prepared statement to protect against SQL injection. You should use this method everywhere.
As Barmar and I noted, your $userName and $passWord variables are being overwritten by the while loop. As such the ID specified in $_GET['add'] and $_GET['delete'] requests will not be associated with the correct $userName.
In order to resolve the issue, you must lookup the user details by the ID associated with the desired add or delete $_GET request.
Note: the use of the object oriented mysqli syntax is used below, as it is less verbose and personally easier for me to read.
<?php
#/var/www/html/home.php
$db = mysqli_connect('localhost', 'root', '(Password)', 'web');
/* ensure an expected action is requested and determine associated ID */
$actionId = null;
if (!empty($_GET['add'])) {
$actionId = $_GET['add'];
} elseif (!empty($_GET['delete'])) {
$actionId = $_GET['delete'];
}
/* execute action before outputting user table (use strict comparison operator !==) */
if (null !== $actionId) {
/* an action was specified - retrieve the associated user details from the database */
if (!$stmt = $db->prepare('SELECT username, password FROM table WHERE id = ?')) {
die('Unable to retrieve user details.');
}
$stmt->bind_param('s', $actionId);
$stmt->execute();
$stmt->bind_result($userName, $passWord);
if (!$stmt->fetch()) {
die('Unknown user specified');
}
/* execute desired add action */
if (isset($_GET['add'])) {
# debug code prevents redirect
die("$userName, $passWord");
$add = '(Too long to display)';
/* use __DIR__ as opposed to full path in case you ever move hosts */
file_put_contents(__DIR__ . "/directory/$actionId.xml", $add);
header("Location: directory/$actionId.xml");
exit;
}
/* execute desired delete action */
if (isset($_GET['delete'])) {
if (!$stmtDelete = $db->prepare('DELETE FROM table WHERE id = ?')) {
die('Error updating record');
}
$stmtDelete->bind_param('s', $actionId);
if (!$result = $stmtDelete->execute()) {
die('Error updating record');
}
/*
* only check file if it was deleted from the database successfully
* use __DIR__ as opposed to full path in case you ever move hosts
*/
deleteLineInFile(__DIR__ . '/table-users.txt', "'$userName'");
# debug code prevents redirect
die('Record updated successfully');
header('Location: home.php');
exit;
}
}
/*
* this is where <html> should start unless you utilize output buffering
* output the HTML and your table data after your request action, to ensure the redirects occur
*/
$email = $row['userEmail']; //retrieved from somewhere else
if (!$stmt = $db->prepare('SELECT id, username, password, activeStatus FROM table WHERE email = ?')) {
die('Unable to retrieve account list');
}
$stmt->bind_param('s', $email);
$stmt->bind_result($userId, $userName, $passWord, $activeStatus);
echo "<center><table border='1'>
<tr>
<th>Username</th>
<th>Password</th>
<th>Active?</th>
<th>Add Account</th>
<th>Delete Account</th>
</tr>";
while ($stmt->fetch()) {
//always escape user supplied values being output to HTML
$userName = htmlentities($userName, ENT_QUOTES, 'UTF-8', false);
$passWord = htmlentities($passWord, ENT_QUOTES, 'UTF-8', false);
$activeStatus = htmlentities($activeStatus, ENT_QUOTES, 'UTF-8', false);
echo "<tr>";
echo "<td>" . $userName . "</td>";
echo "<td>" . $passWord . "</td>";
echo "<td>" . $activeStatus . "</td>";
echo "<td><a href='home.php?add=" . $userId . "'>Add Account</a></td>";
echo "<td><a href='home.php?delete=" . $userId . "'>Delete Account</a></td>";
echo "</tr>";
}
echo "</table></center>";
I also suggest converting your HTML attributes from using single quote ' to using double quote ", to ensure compatibility and uniformity with any other library you may use.
Hello I'm making a shop in php where I populate the shop with a while loop so all the shop items from my database are displayed. This works fine but I have an issue when I try to update the stock count and money left on the account when I press the buy button.
The $ItemCost variable only saves the last populated item cost and I'm not sure how to save the cost of each item to insert it into the database.
Also the $StockCount variable sets the stockcount to 1.
How can I fix this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
}
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money = $NewTotal WHERE ID = $ID";
if(isset($_POST['Buy'])){
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
As #Sean said, you can do this like :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['Buy'])){
// update stock and money
$ID = $_POST['ID'];
$Money = $_POST['Money'];
$ItemCost = $_POST['ItemCost'];
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money =
$NewTotal WHERE ID = $ID";
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
// display items
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER
BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<form method='post' action=''>";
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='hidden' name='Id' value='".$ID."'/>";
echo "<input type='hidden' name='Money' value='".$Money."'/>";
echo "<input type='hidden' name='ItemCost' value='".$ItemCost."'/>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
echo "</form>";
}
}
$conn->close();
Assuming you don't want ajax, and you don't want js, but only a 'buy' button under each item which will reopen the entire page, then you want something like this. This is pseudo code:
//FIRST we need to process the form:
<?php
if(isset($_POST['submit'])){
$itemId = $_POST['id'];
//do the stuff. Remember about escaping $itemId, or using prepared statements
//select... from where id = $itemId
}
?>
//now get the items:
<?php
$GatherItems = ...
?>
//now the html:
<?php
while($row = $result->fetch_assoc()) {
?>
<form method = 'post'>
<div class='test'><?=$ItemName?></div>
...
<input type = 'hidden' name = 'itemId' value = '<?=$ID?>'>
<input type = 'submit' name = 'submit' value = 'Buy'>
</form>
}
?>
I have a problem trying to select the last registered user. I'm trying to print newly registered users to the screen - can anyone help?
<?php
if (isset($_POST['registrovat']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$passwordre = $_POST['passwordrepeat'];
$email = $_POST['email'];
if ($password == $passwordre)
{
if ($username && $email)
{
$password = md5(sha1(md5($password)));
$db_servername = "localhost";
$db_username = "kubaaivcaweb";
$db_name = "insanity";
$db_password = "XXXXX";
$username = $_POST['username'];
$ip = $_SERVER['REMOTE_ADDR'];
$db_conn = mysqli_connect($db_servername, $db_username, $db_password, $db_name);
$query = mysqli_query($db_conn, "INSERT INTO `8` SET username='$username', password='$password', ip='$ip', email='$email'");
echo "Registrace proběhla úspěšně";
}
}
else {
echo "Hesla se neshodují!";
}
}
while ($row = mysqli_fetch_assoc($new))
{
$new = mysqli_query($db_conn, "SELECT * FROM `8` ORDER BY `id` DESC");
echo "<p>Nejnovější uživatel:" . $row['username'] . "</p>";
}
You have put your query inside instead of outside your loop. Your code looks like this:
while ($row = mysqli_fetch_assoc($new)) {
$new = mysqli_query($db_conn, "SELECT * FROM `8` ORDER BY `id` DESC");
echo "<p>Nejnovější uživatel:" . $row['username'] . "</p>";
}
Instead it should look like this:
echo "DEBUG before query<br />"
if (! $new = mysqli_query($db_conn, "SELECT * FROM `8` ORDER BY `id` DESC")) {
echo "DB error: ". mysqli_error($db_conn). "<br />" ;
exit 1;
}
echo "DEBUG after query<br />"
while ($row = mysqli_fetch_assoc($new)) {
echo "<p>Nejnovější uživatel:" . $row['username'] . "</p>";
}
echo "DEBUG after fetch<br />"
I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function