while loop always print last inserted row result - php

Problem is while loop always showing last inserted row result. I've tried this below code to follow/unfollow button option. For example I'm a user id=1. I have already followed user id=4. Now, I want to follow user id=5. When i click follow button(id=5) it turns into Unfollow properly. But, I have already followed user id=4. That turns into Follow. This is my problem.
Then I tried echo $following;. it Prints 5555. That means last inserted data. But I want 45. I'm sure I've made a mistake in my while loop. But I don't know what I should change?
<?php
try
{
$stmt = $conn->prepare("SELECT * FROM users ORDER BY Autoid");
$stmt->errorInfo();
$stmt->execute();
$sth = $conn->prepare("SELECT * FROM followers ORDER BY Autoid");
$sth->errorInfo();
$sth->execute();
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Autoid'] ."</td>";
echo "<td>". $row['Name'] ."</td>";
// echo $row['Following'];
if($_SESSION['sesuname'] == $row['Username'])
{
echo "<td class='itsyou' >Its You ". $_SESSION['sesuname'] ."</td>";
}
else
{
if(($follower == $_SESSION['sesid']) AND ($following != $row['Autoid']))
{
//echo "<td>true</td>";
echo $following;
echo "<td>";
echo "<form id='jsform' method='post' action='subscribe.php'>";
echo "<input type='hidden' name='id' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >Follow</button>";
echo "</form>";
echo "</td>";
}
else
{
//echo "<td>false</td>";
echo "<td>";
echo "<form id='ufform' method='post' action='unsubscribe.php'>";
echo "<input type='hidden' name='uid' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >UnFollow</button>";
echo "</form>";
echo "</td>";
}
}
echo "</tr>";
}
} catch (PDOException $e) {
'Database Error : ' .$e->getMessage();
}
?>

This code:
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
Simply OVERWRITES $following and $follower every time you fetch a row, leaving you with the LAST row fetched in the variables. Perhaps you want something more like
$following[] = $follow_row['Following'];
$follower[] = $follow_row['Follower'];
^^--- append new row value to an array.

Related

How do I update a row of data with a button click

First of all I am kind of new to PHP.
I've been asked to change up a bit of code and add the option to see the status of a field and mark the rows which are completed. So I've added a status field to my MySQL database which has a standard value of 0. Then on button click I'd like this to change to the value 1. Based on this I can either project a cross glyph icon with a button to update this, or project a checkmark so that the status is "done".
Now I'm having issues with the update part. I just cannot seem to get it to work with clicking the button and updating only that row. Field "prdh_num" is my unique value if that is usefull.
Here's the code I work with:
function uren_error(){
global $mysql;
$sql = "
SELECT *
FROM uren_error, medw
WHERE uren_error.uren_datum between adddate(now(),-14) and now() AND medw.medw_num = uren_error.medw_num
ORDER BY uren_error.prdh_num";
$query = $mysql->query($sql);
echo "<h1>Niet in MKG verwerkte uren van de afgelopen 14 dagen</h1>";
echo "<div class='row' id='urenTabel'>";
echo "<div class='col-xs-0 col-md-0'></div>";
echo "<div class='col-xs-12 col-md-12'>";
echo "<table class='table'>";
echo "<thead>";
echo "<th>Verwerkingsdatum</th>";
echo "<th>Medewerker</th>";
echo "<th>Productieorder</th>";
echo "<th>Productieorder regel</th>";
echo "<th>Bewerking</th>";
echo "<th>Duur</th>";
echo "<th>Status</th>";
echo "<th>Actie</th>";
echo "</thead>";
while($row = mysqli_fetch_array($query)){
$hours = floor($row['uren_tijd_man_std'] / 3600);
$mins = floor($row['uren_tijd_man_std'] / 60 % 60);
echo "<tr>";
echo "<td>" .$row['uren_datum']. "</td>";
echo "<td>" .$row['medw_roepnaam'] . " " . $row['medw_tussenvoegsel'] . " " . $row['medw_naam'] . "</td>";
echo "<td>" .$row['prdh_num']. "</td>";
echo "<td>" .$row['prdr_num']. "</td>";
echo "<td>" .$row['bewerk_num']. "</td>";
echo "<td>" .$hours.":".$mins. "</td>";
if($row['uren_status'] == "0"){
echo "<td><div class='glyphicon glyphicon-remove' style='color:red'></div></td>";
echo "<td><form action'' method='POST'><input type='submit' name=".$row['prdh_num']."></input></form></td>";
} else if($row['uren_status'] == "1"){
echo "<td><div class='glyphicon glyphicon-ok' style='color:green'></div></td>";
}
echo "</tr>";
}
echo "</table>";
}
my update code so far:
$productieorder = $row['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
In more simple way you can use <a> tag to update your record ,instead of <form> , just attached your parameter which you need to passed . i.e :
echo "<td><a href='currentphppagename.php?prdh_num=".$row['prdh_num']."'></a></td>";
And to get prdh_num use $_GET on same page i.e :
//check if have some value or not
if (isset($_GET['prdh_num'])) {
//getting value passed in url
$productieorder = $_GET['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
}
And other way using form you can have one hidden field and assign row value to that :
echo "<td><form action='' method='POST'><input type='hidden' value=".$row['prdh_num']." name='prdh_num'/><input type='submit' name='submit'></input></form></td>";
Now on click of submit check below on same page :
//check if have some value or not
if (isset($_POST['submit'])) {
//getting value passed in url
$productieorder = $_POST['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
}
You can do this with javascript. You should put "ondblclick" event on tr tag.
<tr ondblclick="Update(rowno)" />
And in javascript tag, there must be a function like
<script type="text/javascript">
function Uptdate(row) {
window.location.href ="update.php?row="+row;
}
</script>

showing results obtained after $_POST in a new page

I have been trying to work this out for a while.
I have created a form with a dropdown box that gets results from a database. from this i then $_POST that from to another page. From that second page i wish to get the ID number and then get the records and display them on screen.
I will then put them in a table to organise the results better.
can anyone help me in achieving this.
Here is the code for the form (which works and sends the $PlantID)
$sql = "SELECT DISTINCT * FROM PLANTS";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
//********************* Botannical name drop down box
echo "<form name='selection' id='selection' action='profile.php' method='post'>";
echo "<select name='flower'>";
while($row = mysqli_fetch_array($result)) {
$plantid = $row['FlowerID'];
$plantname = $row['Botannical_Name'];
$plantcommon = $row['Common_Name'];
/* $plantheight = $row['Height'];
$plantav = $row['AV'];
$plantcolours = $row['Colours'];
$plantflowering = $row['Flower_Time'];
$plantspecial = $row['Special_Conditions'];
$plantfrost = $row['Frost_Hardy'];
$plantaspect = $row['Aspect'];
$plantspeed = $row['Growth_Speed'];*/
echo "<option value=".$plantid.">".$plantname." -> AKA -> ".$plantcommon."</option>";
}
echo "</select>";
echo "<br />";
//********************* End of form
echo "<input type='submit' name='submit' value='Submit'/>";
echo "</form>";
I have created this page to get the ID and display that ID on screen. AS you can tell i have probably doubled up on ways to try work this out.
$sql = "SELECT * FROM PLANTS";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
if(isset($_POST['submit'])){
$selected_val = $_POST['Botannical_Name']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
echo "<br />";
echo "well:".$_POST["Botannical_Name"]."<br/>";
echo "now:".$plantquery."<br />";
echo $_POST;
echo "<table>";
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
Any help would be greatly appreciated.
you should use following to get the selected value,
$selected_val = $_POST['flower'];
if(isset($_POST['submit'])){
$selected_val = $_POST['flower']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
$sql = "SELECT * FROM PLANTS WHERE FlowerID='.$selected_val.'";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
while ($row=mysqli_fetch_assoc($result))
{
echo $row['Botannical_Name'];
}
}
echo "<br />";
print_r($_POST);
if(!empty(_POST)) {
echo "<table>";
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
}

Retrieve data from sql database and display in tables - Display certain data according to checkboxes checked

I have created an sql database(with phpmyadmin) filled with measurements from which I want to call data between two dates( the user selects the DATE by entering in the HTML forms the "FROM" and "TO" date) and display them in a table.
Additionally I have put, under my html forms, some checkboxes and by checking them you can restrict the amount of data displayed.
Each checkbox represent a column of my database; so along with the date and hour column, anything that is checked is displayed(if none is checked then everything is displayed).
So far I managed to write a php script that connects to the database, display everything when none of my checkboxes is checked and also managed to put in order one of my checkboxes.
Problem: The data that I call for are been displayed twice.
Question: I want to have four checkboxes.
Do I need to write an sql query for every possible combination or there is an easier way?
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_Database_Test = "localhost";
$database_Database_Test = "database_test";
$table_name = "solar_irradiance";
$username_Database_Test = "root";
$password_Database_Test = "";
$Database_Test = mysql_pconnect($hostname_Database_Test, $username_Database_Test, $password_Database_Test) or trigger_error(mysql_error(),E_USER_ERROR);
//HTML forms -> variables
$fromdate = $_POST['fyear'];
$todate = $_POST['toyear'];
//DNI CHECKBOX + ALL
$dna="SELECT DATE, Local_Time_Decimal, DNI FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$tmp ="SELECT * FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$entry=$_POST['dni'];
if (empty($entry))
{
$result = mysql_query($tmp);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>Solar_time_decimal</th>
<th>GHI</th>
<th>DiffuseHI</th>
<th>zenith_angle</th>
<th>DNI</th>
";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
echo "<td>" . $row['Solar_Time_Decimal'] . "</td>";
echo "<td>" . $row['GHI'] . "</td>";
echo "<td>" . $row['DiffuseHI'] . "</td>";
echo "<td>" . $row['Zenith_Angle'] . "</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';}
else
{
$result= mysql_query($dna);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>DNI</th>
";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal']."</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';
}
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();
?>
Try to create your checkbox like below:
Solar_Time_Decimal<checkbox name='columns[]' value='1'>
GHI<checkbox name='columns[]' value='2'>
DiffuseHI<checkbox name='columns[]' value='3'>
Zenith_Angle<checkbox name='columns[]' value='4'>
DNI<checkbox name='columns[]' value='5'>
And try to hange your PHP code to this:
<?php
//HTML forms -> variables
$fromdate = isset($_POST['fyear']) ? $_POST['fyear'] : data("d/m/Y");
$todate = isset($_POST['toyear']) ? $_POST['toyear'] : data("d/m/Y");
$all = false;
$column_names = array('1' => 'Solar_Time_Decimal', '2'=>'GHI', '3'=>'DiffuseHI', '4'=>'Zenith_Angle','5'=>'DNI');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "DATE,Local_Time_Decimal";
}
//DNI CHECKBOX + ALL
$tmp ="SELECT ".implode(",", $sql_columns)." FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$result = mysql_query($tmp);
echo "<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();?>
This solution consider your particular table columns but if your wish a generic solution you can try to use this SQL too:
$sql_names = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database_Database_Test' AND TABLE_NAME = '$table_name'";
and use the result to construct the $column_names array.
Solution for your problem : Change the mysql_fetch_assoc with mysql_fetch_array
If you have the same problem try to print your result with print_r
Answer : Use the bit datatype in mysql for store and read your checkboxes.
When you're receiving thr value from the database then you can use
in the parameter checked you can use the php code as exist :
$value = ...get the value from db ( 1 or 0 )
echo '<input type="checkbox" name="thename" value="thevalue" '.($value==1?'checked=checked'.'').'/>';

mySQL form input, insert by looping, not inserting

I am new to StackOverflow, and relatively new to PHP. I have a mixture of a mySQL table and form input, where a user will enter numbers into a field (options) next to each corresponding record (companyid), then submit and these should be inserted into the mySQL table. If no "options" are entered, the loop should skip and move on.
When I submit, nothing is actually inserted into the database. I need a little help because I have looked at several examples and I thought I had everything correct.
Thank you so much!!
Below is the table with form inputs:
<?php
$result = mysqli_query($connection,"SELECT * FROM company_main");
echo "<form action='userinvestdynamic.php' method='post'>";
while($row = mysqli_fetch_array($result))
{
echo "<table border=1>";
echo "<tr>";
echo "<td>Company ID</td>";
echo "<td>" .$row['company_id'] . "</td>";
echo "<input type=hidden name=companyid[] value=" . $row['company_id'] . " />";
echo "<td><input type=number name=options[]></td>";
echo "</tr>";
echo "</table>";
}
echo "<input name='userinvestoptionsdynamic' type='submit' value='Invest!'>";
echo "</form>";
?>
And here is the code once the form is submitted.
<?php
require ('db_login.php');
session_start();
if (isset($_POST['userinvestoptionsdynamic'])) {
$userid = $_SESSION['login_user'];
$companyid = $_POST['companyid'];
$options = $_POST['options'];
// loop through array
$number = count($_POST['companyid']);
for ($i=0; $i<$number; $i++)
{
//store single company and options in local variables
$companyid = $companyid[$i];
$options = $options[$i];
//run insert for any items that don't have blank options
if($options[$i] <>''){
$query = "INSERT INTO user_company_invested(user_id, company_id, user_company_options_invested) VALUES($userid,$companyid,$options)";
mysqli_query($connection, $query);
}
}
header('Location: userpage.php');
} else {
echo 'error';
}
?>
Explanations are inside the comment /* */
<?php
$result = mysqli_query($connection,"SELECT * FROM company_main");
$counter=0; /* DECLARE THIS BEFORE YOUR WHILE LOOP */
echo "<form action='userinvestdynamic.php' method='post'>";
while($row = mysqli_fetch_array($result))
{
echo "<table border=1>";
echo "<tr>";
echo "<td>Company ID</td>";
echo "<td>" .$row['company_id'] . "</td>";
echo "<input type=hidden name=companyid[$counter] value=" . $row['company_id'] . " />"; /* DECLARE THE COUNTER ON COMPANY ID ARRAY */
echo "<td><input type=number name=options[$counter]></td>"; /* DECLARE THE COUNTER ON OPTIONS ARRAY */
echo "</tr>";
echo "</table>";
$counter=$counter+1; /* ADD 1 EVERY LOOP ON COUNTER */
}
echo "<input type='hidden' name='hiddencounter' value='$counter'>"; /* COUNT ALL THE LOOP AND SUBMIT IT TO THE NEXT FORM */
echo "<input name='userinvestoptionsdynamic' type='submit' value='Invest!'>";
echo "</form>";
?>
userinvestdynamic.php:
<?php
require ('db_login.php');
session_start();
if (isset($_POST['userinvestoptionsdynamic'])) {
$userid = $_SESSION['login_user']; /* I ASSUME YOU HAVE LOGIN_USER SESSION DECLARED IN THE PREVIOUS FILE? */
$companyid = $_POST['companyid'];
$options = $_POST['options'];
$counter = $_POST['hiddencounter']; /* THIS WILL SET AS YOUR COUNTER */
for ($i=0; $i<=$counter; $i++)
{
if(empty($options[$i])){ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else {
/* store single company and options in local variables */
$query = "INSERT INTO user_company_invested(user_id, company_id, user_company_options_invested)
VALUES($userid,$companyid[$i],$options[$i])";
mysqli_query($connection, $query);
} /* END OF ELSE IF NOT EMPTY COMPANY ID */
} /* END OF FOR LOOP */
header('Location: userpage.php');
} /* END OF ISSET USERINVESTOPTIONSDYNAMIC */
else {
echo 'Error!';
}
?>

How To Edit/Delete Stored Data From Database In PHP

EDIT
I have a mysql table with fields as follows:
Products - serial, name, description, price, picture.
the viewproducts.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
echo '<td> Edit</td>';
}
}
echo "</tr>";
echo "</table>";
?>
my edit.php page looks like this:
<?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
}
echo "</tr>";
echo "</table>";
?>
when i click on edit from thr viewproducts.php page, it goes to edit.php page where nothing is showing up. the serial id on the address bar is coming up as follows:
http://www.********.com/****/admin/edit.php?product_id=
I want to be able to edit any product clicked on from the viewproduct.php page and transfered to edit.php page. I dont think my edit.php page is set up corretly.
Please help,
Thanks
You can pass via $_GET the id of the product and then, in the edit/delete page, retrieve that parameter. Obviously you have to sanitize the input properly before using it. For example, the link of the each product should look like this:
echo '<td>Edit</td>';
In the edit page you should have something like:
$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id
You could pass it as an argument to your php file in wich you want to edit/delete the product:
Edit Product
Then in your edit.php you will pick up the id of the product and load it's data from the database.
[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database

Categories