How do I get my to only update whats selected? - php

There are two rows in my table called post. After pressing the button the table updates the row above it and if I click it again it updates that one it's supposed to.
If you press the button it adds 1 to the column. There are two rows, if you click the button for row 2 it will add one to row 1 then if you click it again it will update row 2. Or if you press it for one and try to press it for the other it will update the last one you clicked first and then update the one you wanted it to do.
//The loop echos the row out below
foreach($dbData as $post){
<form method="post" id="liketest" class="redirect" >
<button type="submit" form = "liketest" name="like" value= "'.$post["id"].'">
</button>
</form>
//If you press the button it is supposed to grab the id from the "post" (so the row id) and update count by adding 1
if (isset($_POST['like'])){
$post_id = $_POST['like'];
$result = $conn->query("SELECT * FROM likedpost");
if($result->num_rows == 0) {
$n = "count";
$stmt = $conn->prepare("UPDATE posts SET count = $n+1 WHERE id = $post_id ;");
$stmt->execute();
$stmt->close();
}
}
I expect it to update the row you clicked, but the actual result is it updating the row above it then the one you clicked.

You are violating the uniqueness of an element ID when you have a loop that doesn't generate a dynamic ID. So when you reference a different form with the form attribute, it will not know which one to use. Just drop the form references on your buttons altogether.
You should also be using bounded placeholders when you're using a prepared statement.
foreach ($dbData as $post){
echo '<form method="post" class="redirect" >
<button type="submit" name="like" value= "'.$post["id"].'">
Like this post!
</button>
</form>';
}
if (isset($_POST['like'])){
$stmt = $conn->prepare("UPDATE posts SET count = count + 1 WHERE id = ?");
$stmt->bind_param("s", $_POST['like']);
$stmt->execute();
$stmt->close();
}

<?php
if (isset($_POST['like'])) {
$sql = "SELECT * FROM likedpost";
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if ($count > 0) {
//performed you query
}
}
$sql1 = "SELECT * FROM likedpost";
$dbData=mysqli_query($conn, $sql1);
foreach ($dbData as $post) {
?>
<form method="post" id="liketest" class="redirect">
<button type="submit" form = "liketest" name="like" value="<?php echo $post['id']; ?>">Submit</button>
</form>
<?php
}
This is simple logic you can apply in $count variable you will get number of liked post and after that you can used that $count variable count+1 to update in another table (this is mysqli Procedural way)

Related

How to update through foreach loop

I want to update data of form fields in database through foreach loop. I have two columns in test_table ID and Input. I have fetched data through while loop and also have printed the value. Now I want to update fetched value. Please give some guidance for this.
Here is my code,
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql))
{
while($row = mysqli_fetch_array($result))
{
$inputResult[]=$row;
}
} <form method="POST"> <input type="text" value=<?php
echo $inputResult[0]['Input']; ?> id="$inputResult[0]['ID']"> <input
type="submit" name="submit"> </form> <?php
if (isset($_POST['submit'])
{
$input = $inputResult[];
foreach($input as $inputs => $value)
{
$Sql = "update test_table set Input='$value' where = '$inputs'";
mysqli_query($conn, $sql);
}
} ?>
Please let me know what errors have in my code ? Thanks in advance.
Next solution is very specific to your problem. The input text is the first element in your form, so, in the PHP code, we can get the input's ID and the VALUE by accessing the first item in the array $_POST (changes are pointed by arrows ◄■■■):
<?php
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql)) {
while($row = mysqli_fetch_array($result)) {
$inputResult[]=$row;
}
}
?>
<form method="POST">
<input type="text" value="<?php echo $inputResult[0]['Input'];?>"
name="<?php echo $inputResult[0]['ID'];?>" /> ◄■■■ NAME, NOT ID.
<input type="submit" name="submit" />
</form>
<?php
if ( isset($_POST['submit']) ) {
$value = reset( $_POST ); // ◄■■■ FIRST VALUE IN $_POST (['input']).
$id = key( $_POST ); // ◄■■■ FIRST KEY IN $_POST (['ID']).
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
}
?>
I replaced the attribute id= by name= in the input text, because PHP needs names, not ids.
After we get the first value and the first key, we can insert them into the sql string.
Edit :
Fixed the missing tags (oops!). I think I found the error, it's so little that it's hard to see : pay attention to next line:
▼
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
Do you see the variable on the left : $Sql (the first letter is uppercased). Now let's see the next line:
▼
mysqli_query($conn, $sql);
The same variable is not uppercased, once you fix that, everything works :
▼
$sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
▲

PHP echo list of users from a database depending on category

Depending on the input from checkboxes I'm trying to echo out users in a database based on category in a table linking the users-table with categories. But I only get one result for each category, even though I know there are several users in each category.
I have spent several dies seaching for the correct way to do this, and based upon the many tutoriels and articles out there I thought this method would work. But it does not.
This is the code that doesn't do what I want it to do:
function printusers($idcheck, $cat){
$sqlString = "SELECT userid FROM user_category WHERE categoryid ='$idcheck'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user id.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
// Make the first user on the list visable
mysqli_data_seek($result, 0);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['userid'];
$sqlString = "SELECT name FROM users WHERE id='$id'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
// echo users
echo "<h2 class=\"browsecategory\">Category: $cat</h2>
<p class=\"user\">Name: $name</p>\n";
}
}
if(isset($_POST['admins'])){
printusers(1, "Administrator");
}
I have also tried replacing the while loop with a foreach loop, like this:
foreach ($result as $row) {
same code as in while loop
}
This method echoed out several empty results. The HTML was there, but there was no information from the database. And the number of reults that were echoed was even higher than the number of results that the database should produce.
This is the HTML. A basic checkbox form:
<form action="results.php" method="POST">
<input type="checkbox" name="admins" id="admins">
<input type="checkbox" name="users" id="users">
<input type="checkbox" name="maillist" id="maillist">
<input type="submit" value="Browse">
</form>

generating reference id after form submit

I am trying to generate a reference id like this CTS-P 0 then CTS-P 1 each time a user submits a form and it gets inserted.
what i have came up with is inserting CTS-P 0 to database as i submit.but the problem is its not incrementing CTS-P 0 to CTS-P 1 after i submit again.
i tried to use mysql_insert_id() here is what i have done so far.this is the smallest thing but i could not solve. please have a look
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("dbname",$con);
$genid="";
if(isset($_POST['submit'])) {
$frstname=$_POST["frstname"];
$genid=mysql_insert_id();
$genid .=count($genid);
//echo $genid;
for($i=0; $i<$genid; $i++) {
$sql = "INSERT INTO tblname (`namecol`,`refidcol`) VALUES ('$frstname','CTS-P $genid[$i]')";
$result = mysql_query($sql);
}}
?>
//here is the form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="generate" >
First Name<input type="text" name="frstname" />
<input type="submit" name="submit" value="Submit" />
</form>
it is inserting it in my refid column as CTS-P 0 but not incrementing from next time i submit.i know its very noobish but i am stuck.
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("dbname",$con);
if(isset($_POST['submit'])) {
$frstname=$_POST["frstname"];
$sql = "SELECT * FROM tblname";
$genid = mysql_query($sql, $con);
$genid = mysql_num_rows($genid);
//Since you're using "0" as your first number, I decided to comment this out, if not, uncomment it
//$genid++;
$sql = "INSERT INTO tblname (`namecol`,`refidcol`) VALUES ('$frstname','CTS-P $genid')";
$result = mysql_query($sql);
}
?>

PHP delete row via non PK

I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)

PHP array updating multiple Mysql rows

I've a problem when updating multiple Mysql rows when using an array, Lets start with the following submit form :
$n = array(); //Supplier Name
$s = array(); //Short Name
$o = array(); //Shipment No.
$id = array(); //Supplier ID
<form action="editing_supplier.php" method="post">
<input type="hidden" value="<?php echo $row['id'] ?>" name="id[]">
<input type="text" value="<?php echo $row['name']?>" required name="n[]">
<input type="text" value="<?php echo $row['short_name']?>" required name="s[]">
<input type="text" value="<?php echo $row['shipment_no']?>" required name="o[]">
<input type="submit" value="Confirm Editing" >
</form>
Now when clicking Submit, which directly opens up "editing_supplier.php" page- The following codes are bellow :
if((isset($_POST['n'])) && (isset($_POST['s'])) && (isset($_POST['o']))){
//Shows up the ID for each Supplier Name
if(is_array($_POST['id'])) {
foreach($_POST['id'] as $id){
//Updates Supplier Name
if(is_array($_POST['n'])) {
foreach($_POST['n'] as $value){
$query = "UPDATE suppliers SET name = '".$value."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Short_Name
if(is_array($_POST['s'])) {
foreach($_POST['s'] as $value1){
$query = "UPDATE suppliers SET short_name = '".$value1."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Shipment No.
if(is_array($_POST['o'])) {
foreach($_POST['o'] as $value2){
$query = "UPDATE suppliers SET shipment_no = '".$value2."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//End of for Each id
}
}
What actually Does, When Selecting a single row to update..It works perfectly ! But when doing a multiple selection in-order to make an update for them, it messes up all the values..As if copying the last id,supplier name, short name and shipment no. to all the selected rows.
I think this is due to the series of foreach within the foreach($id). I would write :
foreach($_POST['id'] as $index=>$id) {
to keep track of the index of your record, and then do not do any other foreach but rather :
$query = "UPDATE suppliers SET name = '".$_POST['n'][$index]."' where id ='".$id."'";
so you keep the link between the $id value and the other variables.

Categories