Selecting specific id in foreach loop - php

$result = mysql_query("SELECT * FROM marias_products WHERE product_id = $id ");
$projects = array();
while($rowrow = mysql_fetch_assoc($result)){
$projects[] = $rowrow;
}
foreach ($projects as $project) {
$resultq = mysql_query("SELECT * FROM inventory WHERE product_id LIKE '%".$id."%'");
while($rows = mysql_fetch_array($resultq))
{
$qwerty=$rows['qtyleft'];
}
if ($qwerty!=0)
{
// echo '<input type="text" name="pizasize" value="'.$project['product_size_name'].'"/>';
echo '<input hidden type="text" name="idd" value="'.$project['mp_id'].'"/>';
echo '<tr>';
echo '<td>'.$project['product_size_name'].'</td>';
echo '<td>'.$project['product_price'].'</td>';
echo '<td>'.$project['mp_id'].'</td>';
echo '<td>'.'<input name="but" type="image" value="'.$project['mp_id'].'" src="images/button.png" />'.'</td>';
echo '</tr>';
}
else
{
echo 'not available';
}
}
I'm having a problem with getting the selected 'mp_id' inside in foreach loop. What happen is that once I select by clicking the button. I've selected the last ID of the entire table. Hope someone could help. Ty. Just learning PHP.

Related

Created a Select dropdown option from mysql db but I also want to add a select all option from the same form dropdown PHP

I have a simple form that is using a dropdown list to select a team member by position from a phpmyadmin db and using php in an index.php file.
This returns the rows perfectly and works great, however, I would like to also have the option in the same form to select all records from that table regardless
Here is the html form
<form id="main_select" action="view_members.php" method="POST">
<select name='main_select' required>
<option value="" disabled selected>Select staff position</option>
<option value="all">View All Members</option>
<option value="Professor">Professor</option>
<option value="Senior Lecturer">Senior Lecturer</option>
<option value="Reader">Reader</option>
<option value="Lecturer">Lecturer</option>
</select>
<input type="submit" value="View Selected Staff Members">
</form>
and here is the view_members.php that works perfectly when say a professor option is chosen
<?php
if (isset($_POST['main_select'])) {
$position = $_POST['main_select'];
$statement = "SELECT * FROM staff_members WHERE position = '$position'";
$result = mysqli_query($conn, $statement);
}
?>
<?php
echo '<table align="center" border="0" cellspacing="35" cellpadding="2" width="100%">';
echo "<thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Position</th><th>Update</th>
<th>Action</th></tr></thead>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['email']}</td>";
echo "<td>{$row['position']}</td>";
echo "<td><a href='edit_member.php?id={$row['id']}'>Edit</a></td>";
echo "<td><a href='delete_member.php?id={$row['id']}'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
echo '<p>Back</p>';
?>
I then tried to add an else statement to look for "all" in the form and simply select all records but that returns nothing yet if I choose professor again it works ok? is there a way I can do this?
Here is the if else code I tried with
<?php
if (isset($_POST['main_select'])) {
$position = $_POST['main_select'];
$statement = "SELECT * FROM staff_members WHERE position = '$position'";
$result = mysqli_query($conn, $statement);
} else {
if (isset($_POST['main_select' == 'all'])) {
$statement = "SELECT * FROM staff_members";
$result = mysqli_query($conn, $statement);
}
}
any help would be greatly appreciated.
Thanks
David.
So thank you for your input guys, here is what I put together assuming this is still open to SQL injection?
<?php
if (isset($_POST['main_select'])) {
$position = $_POST['main_select'];
if ($position == "all") {
$statement = "SELECT * FROM staff_members";
} else {
$statement = "SELECT * FROM staff_members WHERE position = '$position'";
}
$result = mysqli_query($conn, $statement);
}
echo '<table align="center" border="0" cellspacing="35" cellpadding="2" width="100%">';
echo "<thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Position</th><th>Update</th><th>Action</th></tr></thead>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['email']}</td>";
echo "<td>{$row['position']}</td>";
echo "<td><a href='edit_member.php?id={$row['id']}'>Edit</a></td>";
echo "<td><a href='delete_member.php?id={$row['id']}'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
echo '<p>Back</p>';
?>
However, it works and pulls in all records when "all" is selected

To fetch the field name along with their values and edit it in php

Is it possible to fetch the field name along with their values from a table dynamically(because i have to select the the table from a drop-down so we can't specify the field-name as field-name may vary from one table to another) and the value should editable so that it can be updated...? if yes how?
Here is my code. I have printed the value but not able to edit,update and format it..
$result = mysqli_query("select * from 2mcom where father_name='Siyaram'");
while (false != ($data = mysqli_fetch_array($result, MYSQLI_ASSOC)))
foreach ($data as $key => $value)
echo "$key: $value <br />";
this is my table:
student_name father_name sub1 sub2
kunwar Siyaram 20 40
Output value of table along with their field name as:
Student_name : kunwar
father_name : Siyaram
sub1 : 20
sub2 : 40
You can pull the column names for each table when you're pulling the tabl enames for the dropdown with a query like this:
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
[AND table_schema = 'db_name']
[AND column_name LIKE 'wild']
Using your values for DB_SERVER, DB_USER, DB_PASS, DB_NAME
Note, you can use the Object oriented style for mysqli.
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
$result = $mysqli->query("select * from 2mcom where father_name='Siyaram'");
OR the Procedural style as with your code. But you must include the $link as follows:
$link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
mysqli_query($link, "select * from 2mcom where father_name='Siyaram'")
The rest of the code:
** UPDATED to show editing **
<?php
mysqli_report(MYSQLI_REPORT_ALL);
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
$afinfo[] = $finfo;
}
?>
<form action="YourForm.php" method="post" >
<?php
$row = $result->fetch_assoc();
foreach ($afinfo as $col){
?>
<?php echo $col->name ?>: <input type="text" name="<?php echo $col->name ?>" value="<?php echo $row[$col->name] ?>"><br>
<?php
}
?>
<input type="submit" value="Send" >
</form>
echo "<table>" ;
$result = mysqli_query("select * from 2mcom where roll_no='138218600004'");
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
foreach($row as $key => $value) {
$name = 'field';
$id = $row['roll_no']; //rename this with your row id, this will give you identifiable input names
echo '<tr><td>';
echo $key . ': ';
echo '</td>';
echo '<form method="POST">';
echo '<td>';
echo '<input type="hidden" name="id[]" value="'. $row['roll_no'] .'"/>';
echo '<input type="hidden" name="column[]" value="'. $key .'"/>';
echo '<input type="text" name="field[]" value="'. $value .'"/>';
echo '</td></tr>';
}
$i++;
}
echo "<tr><td>";
echo'<input type="submit" name="submit" value="submit"/>';
echo "</tr></td>";
echo'</form></table>';

Retrieve from database then display in a drop down

I created a small script that allows the user to select from a drop down where there data is retrieved from the database, My problem is the information retrieve doesnt have an option for the user to select I want the dropdown to show an option to select from the drop down and display something like You selected 1) Name and 2) Surname I also want to retrieve two rows eg. name and surname..... How do I go about displaying?
after he/she has selected
My Code so far
////Selectiong from twoo tables
$query = mysql_query("SELECT * FROM selections ORDER BY id ASC") or die(mysql_error());
$result = mysql_num_rows($query);
// If no results have been found or when table is empty
if ($result == 0) {
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="test.php">';
echo '<select name="id" id="id">';
// Fetch results from database and list in the select box
while ($fetch = mysql_fetch_assoc($query)) {
echo '<option id="'.$fetch['name'].'">'.$fetch['surname'].'</option>';
}
echo '</select>';
echo '</form>';
}
you have to use client side scripting to retrieve what users choose.
You can use jQuery:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#write_in_div').click(function(){
var name = $('#names').val();
var surname = $('#surnames').val();
var email = $('#emails').val();
$('#write_in_div').text("Name: "+name+" - Surname: "+surname+" - Email: "+email);
});
});
</script>
</head>
<body>
<?php require 'content.php';?>
</body>
</html>
with content.php:
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="test.php">';
//Names dropdown:
echo '<select name="id" id="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="id" id="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="id" id="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo "<button id='write_in_div'>Click me!</button>";
echo '</form>';
}
?>

Can't get the value from other textfield except the first one

I use the code from phpwebcommerce's shopping cart tutorial, and I am trying to add a text field for user to insert quantity. Since there are different number of choices for a single product, so I use the while statement to query the sub-items and put a text field plus a add button beside each of them. But it only takes the quantity for the first item, and not the rest. If I insert a quantity for the first item, and click on "add" on any of other items, it will still store the first in my cart, which it should not... I am stuck... can someone help me out?
<?php
function displayprodDetail($pdId)
{
$query = mysql_query("SELECT * FROM product_image WHERE p_id ='$pdId'");
WHILE($datarows = mysql_fetch_array($query))
{
$p_num = $datarows['p_number'];
echo '<h1><span>'.$p_num.' -- $'.$datarows['price'].'</span></h1>';
echo '<div id="prodPic"><img src ="'.$datarows['image'].'"/><br /></div>';
echo '<div id="items">';
$sql = mysql_query("SELECT * FROM items WHERE item_number LIKE '$p_num/%' ORDER BY item_number ASC");
$numProduct = dbNumRows($sql);
if($numProduct > 1)
{
echo '<table border="0" cellspacing="0">';
WHILE($data = mysql_fetch_array($sql))
{
$itemId = $data['item_id'];
$p_num = $data['item_number'];
echo '<tr>';
echo '<td><INPUT TYPE="HIDDEN" NAME="'.$itemId.'" VALUE="'.$itemId.'">'.$p_num.'</td>';
echo '<td> Qty: <input type="number" name="qty" id="qty" style="width:30px"></td>';
$cart_url = "cart.php?action=add&i=$itemId&qty=";
?>
<td><input type="Submit" name="Submit" value="Add" onClick="window.location.href='<?php echo $cart_url; ?>' +document.getElementById('qty').value;" ></td>
<?php
echo '</tr>';
}
echo '</table>';
}
else
{
echo 'Items are currently not available.<br>Contact us for more detail.';
}
echo '</div>';
}
}
?>
Here is the add to cart function:
function addToCart()
{
// make sure the product id exist
if (isset($_GET['i']) && (int)$_GET['i'] > 0)
{
$itemId = (int)$_GET['i'];
}
else
{
header('Location: home.php');
}
if (isset($_GET['qty']) && (int)$_GET['qty'] > 0)
{
$qty = (int)$_GET['qty'];
}
// current session id
$sid = session_id();
// check if the product is already
// in cart table for this session
$sql = mysql_query("SELECT item_id FROM cart_table WHERE item_id = $itemId AND ct_session_id = '$sid'");
if (dbNumRows($sql) == 0)
{
// put the product in cart table
$sql = mysql_query("INSERT INTO cart_table (item_id, ct_qty, ct_session_id, ct_date) VALUES ($itemId, $qty, '$sid', now())");
}
else
{
// update product quantity in cart table
$sql = mysql_query("UPDATE cart_table SET ct_qty = ct_qty + $qty WHERE ct_session_id = '$sid' AND item_id = $itemId");
}
// an extra job for us here is to remove abandoned carts.
// right now the best option is to call this function here
deleteAbandonedCart();
header('Location: ' . $_SESSION['shop_return_url']);
}
since you are naming your input boxes same, that's why its not working as expected, try something like:
<input type="number" name="qty_<?php echo $itemId; ?>" id="qty_<?php echo $itemId; ?>" style="width:30px">...
...
<td><input type="Submit" name="Submit" value="Add" onClick="window.location.href='<?php echo $cart_url; ?>' +document.getElementById('qty_<?php echo $itemId; ?>').value;" ></td>

Using foreach in a while statement

I am not sure if this is possible since I do not have much experience with foreach statements, but this is what I have
<?php $string = file_get_contents('data.xml') ?>
<?php
include("../connect.php");
$xml = new SimpleXMLElement($string);
//Loop trough multiple products
print "<table border='1' bordercolor='#6600FF' style='width='100%' cellpadding='3' cellspacing='3'>
<th>Campaign Name</th><th>Countries</th><th>Rate</th><th>Cash</th><th>Points</th>";
$cats = mysql_query("SELECT * FROM `offer_cats`");
while ($off = mysql_fetch_array($cats)) {
$cnames = array($off['name']);
$cnamess = implode(",", $cnames);
$cname = explode(",", $cnamess);
print_r($cnames);
foreach ($cnames as $category) {
$cat = $category;
}
}
foreach($xml->item as $item) {
$count = count(explode(", ",$item->countries));
if ($count >= 5) {
$country = "ALL INTL";
} else {
$country = $item->countries;
}
$rate = number_format((float)$item->rate, 2, '.', '');
$crates = $rate * 0;
$prates = $rate * 45;
$crate = number_format((float)$crates, 2, '.', '');
$prate = number_format((float)$prates, 2, '.', '');
echo'<tr><td>'.$item->name.'<br /><font color="limegreen" size="2">Incent: '.$item->incent.'</font><br /><select name="req" style="width:200px"><option value ="'.$item->requirements.'">'.$item->requirements.'</option></select>
<select style="width:200px" name="cat" id="cat"><option value="'.$cat.'">'.$cat.'</option></select><input type="button" name="add" value="+" /></td>';
echo '<td>'.$country.'</td>';
echo '<td>'.$item->rate.'</td>';
echo '<td><input type = "text" name="cash" value="'.$crate.'" style = "width:75px" /></td>';
echo '<td><input type = "text" name="points" value="'.$prate.'" style = "width:75px" /></td>';
// echo $item->incent;
// echo '<br/>';
}
?>
</tr>
</table>
I am trying to load all of the categories in this line <select style="width:200px" name="cat" id="cat"><option value="'.$cat.'">'.$cat.'</option></select> but it always loads only the last category in the array. Although I am pretty sure that the implode and explodes aren't really needed, it was an attempt to fix the error, but it was in vain. What exactly am I doing wrong?
Your first loop essentially just keeps overwriting the $cat variable:
foreach($cnames as $category){
$cat = $category;
}
You need to put this loop instead down where you want to loop through and output the options, like
echo '<select style="width:200px" name="cat" id="cat">';
foreach($cnames as $category){
echo '<option value="'.$cat.'">'.$cat.'</option>';
}
echo '</select>';

Categories