PHP/SQL Question regarding updating/deleting in php with a sql database - php

I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"char_id" => $_POST['char_id'],
"char_name" => $_POST['char_name'],
"currency" => $_POST['currency'],
"server_id" => $_POST['server_id'],
"account_id" => $_POST['account_id']
];
$sql = "UPDATE characters
SET
char_name = :char_name,
currency = :currency,
server_id = :server_id,
account_id = :account_id
WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['char_id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$char_id = $_GET['char_id'];
$sql = "SELECT * FROM characters WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':char_id', $char_id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!"; //this happens
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['char_name']); ?> successfully
updated.</blockquote>
<?php endif; ?>
<h2>Edit a character</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>
</label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>

The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.

Related

MYSQL SET UPDATE table from a variable re-asked [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
Need to be able to UPDATE a MYSQL table with string data. Get errors no matter what I try, and I have researched and nothing suggested works in this situation.
'$soldout'
'"$soldout"'
{$soldout}
'{$soldout}'
'"{$soldout}"'
<?php
/**
* Use an HTML form to edit an entry in the
* consignitem table.
*
*/
require "../config.php";
require "../common.php";
if (isset($_POST['submit'])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST['itemnumber'];
$item =[
"itemnumber" => $_POST['itemnumber'],
"itemdescription" => $_POST['itemdescription'],
"reserve" => $_POST['reserve'],
"amount" => $_POST['amount'],
"qtyavail" => $_POST['qtyavail'],
"qtybought" => $_POST['qtybought'],
"buyernumber" => $_POST['buyernumber'],
"sold" => $_POST['sold'],
];
/* following is manipulation section including debug lines as echo of data*/
$qtyav = $_POST['qtyavail'];
$qtybo = $_POST['qtybought'];
$amt = $_POST['amount'];
echo "Quan Avail $qtyav<br>";
echo "Quan Bou $qtybo<br>";
echo "AMT $amt<br>";
$amttot = $qtybo * $amt;
echo "AMTTOT $amttot<br>";
$newqty = $qtyav - $_POST['qtybought'];
echo "NewQty $newqty<br>";
if ($newqty < "1") {
$soldout = "y";
echo "soldout $soldout<br>";
} else {
$soldout = "n";
echo "soldout $soldout<br>";
}
/* End Manipulation.
Try adding field for quantity available, then do math.
*/
$sql = "UPDATE consignitem
SET itemnumber = :itemnumber,
itemdescription = :itemdescription,
reserve = :reserve,
amount = :amount,
qtyavail = {$newqty},
qtybought = :qtybought,
buyernumber = :buyernumber,
sold = :sold
WHERE itemnumber = :itemnumber";
$statement = $connection->prepare($sql);
$statement->execute($item);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['itemnumber'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_GET['itemnumber'];
$sql = "SELECT * FROM consignitem WHERE itemnumber = :itemnumber AND sold = 'n'";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->execute();
$item = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!";
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['itemnumber']); ?> successfully updated.</blockquote>
<?php endif; ?>
<h2>Sell an item</h2>
<form method="post">
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table>
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<?php foreach ($item as $key => $value) : ?>
<tr><td><?php echo ucfirst($key); ?></td><td><input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'serial' ? 'readonly' : null); ?><?php echo ($key === 'salenumber' ? 'readonly' : null); ?><?php echo ($key === 'itemnumber' ? 'readonly' : null); ?> <?php echo ($key === 'lotnumber' ? 'readonly' : null); ?><?php echo ($key === 'category' ? 'readonly' : null); ?><?php echo ($key === 'itemdescription' ? 'readonly' : null); ?><?php echo ($key === 'reserve' ? 'readonly' : null); ?><?php echo ($key === 'sellernumber' ? 'readonly' : null); ?><?php echo ($key === 'paid' ? 'readonly' : null); ?>></td></tr>
<?php endforeach; ?>
</table>
<?php echo ($key === 'itemnumber');?>
<br>
<button type="submit" name="submit"><b><h3>Sell the Item</h3></b></button>
</form>
<br>
Back to Item List<br>
<?php require "templates/footer.php"; ?>
UPDATED- - -
Original post:
In the section where sql = UPDATE SET:
Where it says sold = :sold,
I need it to take the variable $soldout and use it to update the field for sold in the table. The one above it for $newqty works fine but when I change the sold one from sold = :sold to sold = , I get an error about number of items doesn't match number of bound items or some such. And it doesn't update the table. Leaving it as sold = :sold works but just doesn't update the sold field.
I have researched using a string in there but nothing I try works.
I know my code is horrible, but this is the first time I have ever tried using PHP with a MYSQL database, and the first time ever to work with a MYSQL database at all. I know it is subject to injections and all that. . once I get it working, I can then figure out how to secure it better.
Thank you in advance!
UPDATED INFO - - -
This script works perfectly for every thing except changing the sold from 'n' to 'y' in the table.
The
qtyavail = {$newqty},
line works so why doesn't
sold = {$soldout}
work? It is the same format as the qtyavail one and the variable $soldout is set just a few lines from the qtyavail one but it is eluding me why it won't work.
Thanks again for any insight!
You don't have a :sold placeholder in the query. And you're calling bindValue() incorrectly; you should call it the same way for :sold as you do for :itemnumber.
$itemnumber = $_GET['itemnumber'];
$sql = "SELECT * FROM consignitem WHERE itemnumber = :itemnumber AND sold = :sold";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->bindValue(':sold', $soldout);
$statement->execute();
You also have a problem with the UPDATE query. $item contains
"qtyavail" => $_POST['qtyavail'],
but the query contains
qtyavail = {$newqty},
You should change the query to
qtyavail = :qtyavail,
and set
$item['qtyavail'] = $newqty;
first of all check wrong quotes in"
$statement->bindValue(':sold, "{$soldout}"');
Most probably should be :
$statement->bindValue(':sold', "{$soldout}");

Add 'delete' button to php results table

I outputted the results of a MySQL table to an HTML table, I'm trying to add a Delete button to remove the user but it doesn't work.
HTML form code:
<?php
$response = $bdd->query('SELECT * FROM users');
$i = 1;
while ($datas = $response->fetch()) {
?>
<tr>
<td><?php echo $datas['first_name']; ?></td>
<td><?php echo $datas['last_name']; ?></td>
<td>
<form action="_delete.php?id=<?php echo $datas['id']; ?>" method="post">
<input type="hidden" name="name" value="<?php echo $datas['id'];?>">
<input class="btn btn-danger" type="submit" name="submit" value="X">
</form>
</td>
</tr>
And this is my _delete.php :
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'root', 'root');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
<?php
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
//sends the query
mysql_query ($query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
?>
My result url is good /_delete.php?id=13 but Delete script isn't.
I have this error: Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future
Any idea?
Your messing around with GET and POST params. You defined a get param named id containing your id and a post param named name containing also your id.
But currently you are trying to access the get param with $_POST (which contains only post params).
To solve your problem, you should use $_GET['id'] or $_POST['name'].
In each way, keep in mind to protect you input from sql injections. Currently the user could pass anything else as well. A simple cast to an int, would be enough.
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
I have incoporated a few suggestions in my answer, try and see if it works.
Create a connection, then get the ID using $_GET instead of $_POST.
<?php
$con=mysqli_connect("localhost","dbuser","dbpassword","dbname");
if($con==false){
die("ERROR:Could not connect.". mysqli_connect_error());
}
else{
$id=$_GET['id']
$query = "DELETE FROM users WHERE id='$id' LIMIT 1";
//sends the query
mysql_query ($con,$query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
}
?>

How to insert every value of array variable in database

How to insert every value of array variable in database, whenever i try to insert value using array variable it gives me a error "Array to string conversion".Actually i want to store the attendance of students into "attendance database table", i am retrieving id and name of students from students database, this information of students is being stored in array but when i use array variable"$result" to insert the name of student into attendence_tbl database it gives me error of array to string conversion.
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange">Attendance Form</span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");?>
<div class="form-container">
<form method="post" action="" role="form">
<!-- <div class="container"> -->
<div class="col-lg-3">
<div class="form-group">
<?php
$qs=mysql_query("select * from student_table");
?>
<table border=1>
<?php
$c=0;
while($stid=mysql_fetch_row($qs))
{
?>
<tr>
<td ><?php echo $stid[0]?></td>
<td><?php echo $stid[1]?></td>
<td>
<select name="present[]" >
<option value=""> ---Select Attendence--- </option>
<option value="P"> Present </option>
<option value="A"> Absent </option>
</select></td>
</tr>
<?php
$stud= $stid[0];
$subj= $stid[1];
$location_vars = array(/*"stud" ,*/ "subj");
$result[] = compact("nothing_here", $location_vars);
$date = date('Y-m-d H:i:s');
$c++;
}
// echo "</select>"."<br>";
echo $c;
$e=0;
if(isset($_POST['present'])){
foreach($_POST['present'] as $present){
print_r($result);
$query=mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES('$stud','$stid','$present','$date')");
$e++;
}}
?>
</table>
</div>
</div> <!--col-lg-4-->
<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>
</form>
</div> <!--form-container-->
</div><!--container-->
</body>
</html>
Seems you want to put an array variable data directly into table which is supposed to throw error,
Here is the solution.
For adding all value of an array directly into table you have to use first convert array into json and then need to insert it into database. like this..
$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");
AND if you want to add all array value into database for each value per row separately then you have to make sure run the loop and then insert each value into database for each record.
If I understand you right you want to upload something like this:
Array([1] => '1', [2] => '2')
into a table, which would not work. So you'd have to use JSON to stringify the array. Example:
<?php
$value = 'Some string';
$value2 = 'Some other string';
$values = Array('String 1', 'String 2', 'String 3');
$json_values = json_encode($values);
$mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server
// Checking if connection was successfull
if( $mysqli->connect_errno ){
echo 'There was an error connection to the SQL Server<br>';
echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
exit; // FAIL
}
// Preparing a statement
$stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');
// Checking if php prepared the statement successfully
if(!$stmt){
echo 'There was an error preparing the statement!';
exit;
}
if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
echo 'There was an error binding params to the statement!';
exit;
}
$stmt->execute();
?>
to post arrays into DB I use this approach:
//database connection class
class Database{
// specify your own database credentials
private $host = "YOUR HOST";
private $db_name = "DATABASE NAME";
private $username = "USERNAME";
private $password = "PASSWORD";
public $conn;
// get the database connection
public function getConnection(){ $this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
//model class
class Model{
// database connection
private $conn;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// add info to db
function create($fieldset){
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query to insert record
$query = "INSERT INTO
tbl_attendence
SET
$fieldset";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
//part that will handle the post
// get database connection
$database = new Database();
$db = $database->getConnection();
//instatiate model
$model = new Model($db);
//function that will filter posted values
function filter($value){
$value = trim($value);
$value = strip_tags($value);
$value = stripslashes($value);
$value = htmlentities($value);
return $value;
}
if(!empty($_POST)){
//Get Variables
foreach($_POST as $key => $value){
//this part will tackle values which are arrays
if(is_array($value)){
$val=implode(",",filter($value));
$groupVal[] = $val;
$groupKeys[] = $key;
}
else{
$groupVal[] = $this->filter($value);
$groupKeys[] = $key;
}
}
//count items in array to establish a limit
$limit = count($_POST);
//arranges the data into "key = value" format
for($i=0;$i<$limit;$i++){
$prepFieldset[$i] = "$groupKeys[$i] = $groupVal[$i]";
}
//prepares the fieldset to be used in SQL query
$fieldset = implode(",",$prepFieldset);
//process them in the model
$status = $model->create($fieldset);
//show response
if($status == true){
$response = 'Data saved';
}
else{
$response = 'Error when saving data';
}
}

Trying to Delete the data displayed in my tables

I have been able to display the data from my database on to my website and I'm trying to delete a single row.
Now the button works but it completely deletes everything as you may tell from the code.
I have no idea on how to assign the delete button to a specific row in my table, where it just deletes that data in that specific row.
On top of this I have one delete button that sits upon my table and have no clue on how to set separate delete buttons for each row given.
admin.php (Displaying my data)
<?php
echo "<table style='box'>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Role</th>
<th>Email</th><th>Username</th><th>Delete</th><th>Amend</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='box'>" . parent::current(). "</td>";
}
function beginChildren(){
echo "<tr>";
}
function endChildren(){
echo "</tr>";
}
}
require 'connection.php';
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v){
echo $v;
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" action="delete.php">
<input <input class="btn-default" type="submit" name="login" value="Delete">
</form>
<?php
echo "</table>";
?>
delete.php
<?php
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I would show an image but I don't have enough reputation points to display it.
The WHERE clause in your DELETE statement will always return to true. On every row, ID will always equal ID. Hence, everything is deleted. You need to pass a parameter to delete script to filter on the row you want deleted. You can do so by a hidden HTML input value using get="method" of <form>.
However, the key is how to obtain that id from webpage's select query. Additionally, you will want to put the input button at the end of each row to delete the corresponding row's id. For these two items, you might have to return to traditional loop onto web page instead of the RecursiveArrayIterator() because we need to add a non fetched object (form delete button) into table.
admin.php (notice form button as last table cell of each row)
...same code as above...
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()) {
?>
<tr>
<td style="box"> <?php echo $row['id']; ?></td>
<td style="box"> <?php echo $row['FirstName']; ?></td>
<td style="box"> <?php echo $row['LastName']; ?></td>
<td style="box"> <?php echo $row['Role']; ?></td>
<td style="box"> <?php echo $row['Email']; ?></td>
<td style="box"> <?php echo $row['Username']; ?></td>
<td>
<form method="get" action="delete.php">
<input type="hidden" name="rowid" value="<?php echo $row['id']; ?>">
<input class="btn-default" type="submit" name="login" value="Delete">
</form>
</td>
<tr>
<?php
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
delete.php (notice $id generated from $GET() and used in delete query)
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// OBTAIN ROWID FROM $_GET
if(isset($_GET['rowid'])) {
$id = $_GET['rowid'];
}
// DELETE SPECIFIED ROW
$sql = "DELETE FROM users WHERE id = ".$id;
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Trying to follow what you have. Have you tried setting the id to a var before doing?
$sql = "DELETE FROM users WHERE id = id";
Example:
$sql = "DELETE FROM users WHERE id = '$id'";
One problem is that your DELETE statement does not include a variable.
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
You need something more like:
//sql to delete record.
$sql = "DELETE FROM users WHERE id = " . $id;
where $id is defined with the ID of the selected row.
Let's address another "hidden" problem.
Now the button works but it completely deletes everything as you may tell from the code.
Given the fact that you said this deletes ALL the records, I would guess that the id of each of your rows is the string 'id' and not a unique integer value.
DELETE FROM {table} WHERE id = {number} does not delete ALL records. It only deletes records matching the condition. You should make sure that you are setting id's correctly when adding rows. The id column should have the following properties: INT UNSIGNED NOT NULL AUTO_INCREMENT.

Execute query update with form from a query

I am trying to create a button on my user list page to delete that row, or make that user an admin.
Here is the info for the user query and html:
<?php
$query = "SELECT * FROM users";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row) : ?>
<?php
if($row['usertype'] == 2) {
$usertype = "<span style='color:#F7FE2E;'>Donator</span>";
} elseif($row['usertype'] == 3) {
$usertype = "<span style='color:red;'>Admin</span>";
} elseif($row['usertype'] == 4) {
$usertype = "<span style='color:orange;'>Owner</span>";
} else {
$usertype = "<span style='color:#585858;'>Normal</span>";
}
?>
<tr>
<!--<td><?php echo $row['id']; ?></td>-->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<!--<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8');?></td>-->
<td><?php echo htmlentities($row['steamid'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo $usertype?></td>
<td><form action="" method="post">
<input type="submit" name="admin" value="Promote" />
</form></td>
</tr>
<?php endforeach; ?>
And the code where I prepare and execute my update query:
if(!empty($_POST['admin']))
{
$query = "UPDATE `users` SET `usertype` = '3' WHERE `id` = " . $row['id'];
// $query_params = array(':id' => $row['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
}
Unfortunately I when I run this current setup, it updates the very last row. To further ask what I am looking for, is I have a list of users:
where "admin_b" is a button that forced $_POST['admin']
Billy admin_b
Bob admin_b
Jill admin_b
Jack admin_b
UPDATE:
So in my form I have an input with <input type="hidden" name="id" value="<?php $row['id']; ?>" /> and added this to my SQL $query = "UPDATE users SET usertype = '3' WHERE id = :id"; $query_params = array(':id' => $_POST['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
send an id with $_POST request, now you are always update user with id = $row['id']
WHERE `id` = " . $row['id'];
row[id]edit?=edit.php= ...
and let's say you have list all the members and beside them is an href, the code above will execute, it will display let's say Billy?edit.php=1, wherein 1 is his primary key, then for the next, when you scroll the cursor to the next href of the next user, Jim, it will display, Jim?edit.php=2, in your edit.php,
if(isset($_POST['edit])){
code goes here to make the user an admin..
You can also make an href for the delete, similar to this edit..
This is just an idea/hint that I can give to you, but your problem can be solved in many different ways, it just depends on your approach on how you could do it :D goodluck.

Categories