So in this part of the website i'm making an edit person information page and if there are more than one person with the name searched you get a table with all the persons; you choose the needed one and edit it in another page.
I need to pass the array that matches with the person selected. I don't know how to pick the array in the other page through POST. This is a part of code of the page that sends the array:
$squery=mysqli_query($conn,"SELECT * FROM amico WHERE (Nome= '" .
$nome . "') AND (Cognome ='" .$cognome. "')");
$num = mysqli_num_rows($squery);
$i=0;
$array= array();
while($rowa=mysqli_fetch_assoc($squery)){
$array[$i]=$rowa;
$i++;
}
$ssquery=mysqli_query($conn,"SELECT * FROM amico WHERE (Nome= '" .
$nome . "') AND (Cognome ='" .$cognome. "')");
if($num > 1) {
echo 'Trovato più di un elemento';
echo '<table border="1">';
echo '<tr>';
echo '<td><p>S</p></td>';
echo '<td><p>Nome</p></td>';
echo '<td><p>Cognome</p></td>';
echo '<td><p>Città</p></td>';
echo '</tr>';
$i=0;
echo '<form method="POST" action="moficatr.php">';
while ($row = mysqli_fetch_array($ssquery)) {
echo '<tr>';
echo '<td> <p> <input type="Radio" name="persona" value="'.
$rowa[$i] . '"></p></td>';
echo ' <td><p>' .$row['Nome'] . '</p></td>';
echo '<td><p>'.$row['Cognome'].'</p></td>';
echo '<td><p>'.$row['Citta'].'</p></td>';
echo '</tr>';
$i++;
}
echo '</table>';
echo '<br><br><input type="submit" value="Modifica"></form>';
}
You can simply pass the selected user's ID to the next page and then fetch all the details using the ID from that page instead of sending the whole array of data to the other side.
Why are you executing the same query twice in your code ? you only need one query which will give you all the data.
Also I strongly encourage you to use PDO please - http://php.net/manual/en/book.pdo.php Or at least prepared statments which is supported in MySQLi as well
$ssquery=mysqli_query($conn,"SELECT * FROM amico WHERE (Nome= '" .
$nome . "') AND (Cognome ='" .$cognome. "')");
$num = mysqli_num_rows($ssquery);
if($num > 1) {
echo 'Trovato più di un elemento';
echo '<table border="1">';
echo '<tr>';
echo '<td><p>S</p></td>';
echo '<td><p>Nome</p></td>';
echo '<td><p>Cognome</p></td>';
echo '<td><p>Città</p></td>';
echo '</tr>';
echo '<form method="POST" action="moficatr.php">';
while ($row = mysqli_fetch_assoc($ssquery)) {
echo '<tr>';
echo '<td> <p> <input type="Radio" name="persona" value="'.
$row['id'] . '"></p></td>'; //you can change 'id' with your column name if it's different
echo ' <td><p>' .$row['Nome'] . '</p></td>';
echo '<td><p>'.$row['Cognome'].'</p></td>';
echo '<td><p>'.$row['Citta'].'</p></td>';
echo '</tr>';
$i++;
}
moficatr.php
//Set up a Mysql connection.
$user_id = (int) $_POST['persona'];
//Query the db to fetch all the details of this user.
$query = "SELECT * from your_table where id=?";
//Prepare statment and execute.
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $address,...);
echo $name;
echo $address;
Related
I am new to php and need some help please.
I'd like to create a simple php while loop.
Inside the loop I want to be able to add or subtract values.
My code seems to be doing what I want, except that i do not know what to put in the $count variable.
The aim is to have one table, and inside that table either add or subtract values of 5.
Here is my code.
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["userName"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "<td>" . $row["balance"] . "</td>";
$count = $row["id"];
?>
<td>
<form name="form" method="post" action="">
<input type="submit" name="add" value="+">
<input type="submit" name="subtract" value="-">
<?php
if (isset($_POST['add'])) {
$sql2 = "UPDATE users SET balance = balance + 5 where id = $count ";
$result2 = $conn->query($sql2);
}
if (isset($_POST['subtract'])) {
$sql2 = "UPDATE users SET balance = balance - 5 where id = $count";
$result2 = $conn->query($sql2);
}
echo $row["id"];
?>
</form>
</td>
</tr>
<?php
}
} else {
echo "0 results";
}
?>
You must send the row id back to the php script, not just the action 'add' or 'subtract'. You can identify the row by the id you want to update. The code will look something like this:
if (isset($_POST['id'], $_POST['add'])) {
$stmt = $conn->prepare('UPDATE users SET balance = balance + 5 WHERE id = ?');
if (!$stmt) {
die('Prepare failed: '.$conn->error);
}
$stmt->bindParam('d', $_POST['id']);
$result = $stmt->execute();
if (!$result) {
die('Execute failed: '.$stmt->error);
}
}
if (isset($_POST['id'], $_POST['substract'])) {
// ...
}
You add this code before the while loop and remove the existing query stuff from inside the while loop.
I am writing an application to build a chart using the google chart API.
The data is dynamic, and resides in a MySQL database.
The issue being faced is that the array that contains the datasource to be displayed only contains the first row returned by the query. Even after looping.
This is the code:
include 'connect.php';
$sql="SELECT result,COUNT(result) value
FROM test
WHERE result LIKE 'GY%'
GROUP BY result";
$result=mysqli_query($link,$sql);
$myurl[]="['Option','Value']";
while($row=mysqli_fetch_assoc($result))
{
$result=$row['result'];
$value=$row['value'];
$Title="My Results";
$myurl[]="['".$result."',".$value."]";
}
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
<?php
echo (implode(",",$myurl));?>
]);
var options={
title:'<?php echo($Title);?> '
};
Only the first row being returned is used in the chart,therefore it shows that value as 100%. How can i ensure ALL the row values are used?
Modify the query like this
$sql="SELECT result value
FROM test
WHERE result LIKE 'GY%'
GROUP BY result";
$result=mysqli_query($link,$sql);
And the number of results you can access like below.
mysqli_num_rows($result)
If you want an associative array, use this:
$query = "SELECT column FROM `table` WHERE id='" . $id . "'"; / Whatever your query is
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
You can then call $row and the column name from the row with a numbered id that is $id by using $row['columnname']; I'm also pretty sure that you can use print_r($row['columnname']); without including the WHERE id='" . $id . "'"; in the query and instead just having $query = "SELECT column FROMtable; and it will print out all of the data (every row) in that column.
Also, if you're just looking to draw data to a chart, using a google API could over complicate things, as you could just output the data to an HTML table with this code:
<?php
$query = "SELECT FROM `table`";
$result = mysql_query($query);
echo '<table class="table">';
echo '<tr class="table">';
echo '<th class="table">Column</th>';
echo '</tr>';
while($row = mysql_fetch_assoc($result)
{
echo '<tr class="table">';
echo '<th class="table">' . $row['column'] . '</th>';
echo '</tr>';
}
echo '</table>';
?>
Add any other things you need using echo in php then the html code. You can also put buttons in the table, and pretty much anything else. This site should give any more info you would need on HTML tables: http://www.w3schools.com/html/html_tables.asp
Here's another little example I made of an HTML form echoed in php. It has buttons, etc.
$query = "SELECT * FROM `users` WHERE status='accepted'";
$result = mysql_query($query) or die(mysql_error());
echo '<table class="table">';
echo '<h2>Accounts</h2>';
echo '<tr class="table">';
echo '<th class="table">Name</th>';
echo '<th class="table">Email</th>';
echo '<th class="table">Username</th>';
echo '<th class="table">Date Created</th>';
echo '<th class="table">Decline</th>';
echo '<th class="table">Accept</th>';
echo '<th class="table">Give Admin</th>';
echo '</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr class="table">';
echo '<th class="table">' . $row['name'] . '</th>';
echo '<th class="table">' . $row['email'] . '</th>';
echo '<th class="table">' . $row['username'] . '</th>';
echo '<th class="table">' . $row['trn_date'] . '</th>';
echo '<form method="post">';
echo '<th class="table"><input type="submit" name="decline_' .$row["id"]. '" value="decline" ></input></th>';
echo '<th class="table"><input type="submit" name="accept_' .$row["id"]. '" value="accept" ></input></th>';
echo '<th class="table"><input type="submit" name="giveadmin_' .$row["id"]. '" value="accept/give admin" ></input></th>';
echo '</form>';
echo '</tr>';
}
echo '</table>';
Hope that helped:)
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'.'').'/>';
Hi I am having trouble getting this to store the value when submitted and then using it in my next query. The drop down is populated fine, but it is either not storing the value or the way I am using it dynamically in my query is wrong. Any help is appreciated. I know I am probably missing something obvious or small, I am new to php.
drop down box
$sth = $db->prepare("SELECT DISTINCT WEEK FROM Player_Points_2013");
//$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$sth->execute();
echo '<form method="POST" action=" " >';
echo '<select id="week" name="week"><OPTION>';
echo "Select a Week to see the stats</OPTION>";
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo "<option value=\"$WEEK\">" . $row['WEEK'] . "</option>";
}
echo '</SELECT>';
echo '<input type="submit" name="table_stats" value="Submit"/>';
echo '</form>';
$select_val = $_POST['week'];
//use value from drop down to display weeks stats
if(isset($_POST['table_stats'])){
$sql = $db->prepare("SELECT PName,CombinedPoints FROM `Player_Points_2013` WHERE
WEEK = '$select_val' ORDER BY CombinedPoints ");
//$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$sql->execute();
Print "<table border cellpadding=10 width=500>";
Print "<tr><th>Player</th><th>Points</th></tr>";
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
Print " <td>".$row['PName'] . "</td> ";
Print " <td>".$row['CombinedPoints'] . "</td> </tr>";
}
Print "</table>";
}
else {
echo $select_val;
}
?>
Use either $row or $info but not both, e.g.:
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
Print " <td>".$row['PName'] . "</td> ";
Print " <td>".$row['CombinedPoints'] . "</td> </tr>";
}
Also you have code:
echo "<option value=\"$WEEK\">" . $row['WEEK'] . "</option>";
What is $WEEK? Maybe it should be $row['WEEK'] instead?
I am posting from a form that selects products from a list, to a page with the selected products displayed. I want to have a link next to each item for removing an item from the selected list (array).
How do I do that? I seem to be losing the session once I click on the remove link.
session_start();
foreach($_SESSION['id'] as $key => $value){
$array = explode(',', $value);
if($value[0]!=''){
$id = $array[0];
$query = "SELECT * FROM products WHERE id = '$id'";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$product_id = $row['id'];
echo '<tr valign="bottom">';
echo '<td>' . stripslashes($row['category']) . '</a></td>';
echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
echo '<td class="right">' . stripslashes(number_format($row['points'], 2)) . '</a></td>';
echo '<td>Remove</td>';
echo "</tr>\n\n";
$points = stripslashes($row['points']);
#$points_total += $points;
}
}
}
$postid = $_POST['id'];
$_SESSION['id'] = $_POST['id'];
$product_id = htmlspecialchars(#$_GET['id'], ENT_QUOTES, 'UTF-8');//the product id from the URL
$s = $_SESSION['id'];
$s = htmlspecialchars(#$_GET['key'], ENT_QUOTES, 'UTF-8');//the product id from the URL
$action = htmlspecialchars(#$_GET['action'], ENT_QUOTES, 'UTF-8'); //the action from the URL
switch($action) {
case "remove":
unset($array[$id]); //remove $product_id from the array with
echo $action . $product_id;
break;
}
Here's the HTML for the form:
<form method="post" action="products_selected.php">
<?php
$query = "SELECT * FROM products ORDER BY rangeCode, category ASC";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
echo '<tr valign="bottom">';
echo '<td>' . stripslashes($row['rangeCode']) . '</td>';
echo '<td>' . stripslashes($row['category']) . '</a></td>';
echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
echo '<td>' . number_format($row['points'], 2) . ' points ';
echo '<input type="checkbox" name="id[]" value="' . $id . '" /></td>';
echo '</tr>' . "\n\n";
}
mysqli_close($dbc);
?>
<tr><td colspan=13><input type="submit" name="submit" value="Order" /></td></tr>
Ok. After a bit of chat and co-working around this issue, we found some problems.
There's the need to insert a check around the code that uses $_GET and $_POST data, to avoid unwanted modification to other variables (an example: when the user clicks "Remove" to remove an item from his choices, the $_SESSION array will be updated with the $_POST array; since this contains nothing, the session array is emptied (and this was why the session was thought to be lost):
To find and delete the item from the session, we have to use the key retrieved from url and check if it's present into the session array. This can be seen in the code below.
if (isset($_POST['id']))
{
$_SESSION['id'] = $_POST['id'];
}
if(isset($_GET['key']) && ($_GET['action'] == 'remove'))
{
if (array_key_exists($_GET['key'], $_SESSION['id']))
{
unset($_SESSION['id'][$_GET['key']]);
}
}
Some other minor changes have been made to the code, but the main problems were the ones explained.