Array is not populating the first record - php

I have this array populating from mysql. But it is not showing me the first record. I can't figure out what the problem is. It should be simple. Here is the code.
$result=mysql_query("SELECT user_instance.instance_name, user_instance.host_name FROM
dba_account, user_instance WHERE dba_account.account_id = user_instance.account_id AND
dba_account.account_id = '1'");
echo mysql_error();
$nume = mysql_fetch_row($result);
while($note = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><input type='text' name='instance_name' class='instance_name'
disabled='disabled' value='$note[instance_name]' size='25' /></td>";
echo "<td><input type='text' name='host_name' class='host_name' disabled='disabled'
value='$note[host_name]' size='25' /></td>";
echo "</tr>";
}

You're fetching the first row in $nume = mysql_fetch_row. That pulls the first record. Then you're iterating through the rest of the records in your while loop. Remove that first line.

The first time you call mysql_fetch_row(), it advances the result resource pointer to the second result. Don't do that. Especially considering you are not using the variable $nume in your loop in any way, it is unnecessary and harmful to your logic.
// Don't do this!
//$nume = mysql_fetch_row($result);
// Instead just fetch the loop
while($note = mysql_fetch_array($result)) {
// etc...
}

Related

PHP & SQL - Update query fails to update value

I'm trying to create a very easy stock managing system. I'm able to show all the items in my table 'parts' and i'm showing the amount in a textbox. However, when i change the value from, for example, 0 to 5 in the textbox and i press my submit button, it doesn't update the stock.
Below is my code, i don't have alot of experience with update querys but i've read about it on php.net, obviously.
<?php
echo "<table width=\"800\" class=\"nieuws\">";
$db=mysqli_connect("localhost","root","","lichtwinkel");
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<form method='post' action=''>";
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal' value=$row[voorraad] /></td>";
echo "<td><input type='submit' id='update' name='update' value='Update' /></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['aantal']) && $_POST['update']) {
$y = $_POST['aantal'];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '$y' WHERE partnr = $row[0]");
}
echo "</form>"
?>
Simply said, what i'm trying to achieve is the following:
Whenever i change the value displayed in the texbox, and i press my submit button, i want it to update the value in the database.
Does anyone know what i'm doing wrong? Any ideas? Articles i should read?
All help would be appreciated.
Thank you.
As i see, you were doing it wrong at all.
First you can't use form tag within more then one td element.
You were didn't close the form tag, only at end. (So if it loops 6 times, you will have 6 forms open, but one ended!).
At update, you're selecting row[0] - it's outside of loop with rows?
Even if you update it, it will show wrong results again. Update should be above selects! So it picks up newly updated value.
What to do:
First make one form for all updates.
Use your submit button to have value DATABASE_ID.
Make the name of "aantal" to "aantalDATABASE_ID".
At submit check for $_POST['update'], and use it's value (DATABASE_ID) to get input $_POST["aantal".$_POST['update']].
Do update, you have all you need.
Example:
<?php
echo "<form method='post' action=''>";
echo "<table width=\"800\" class=\"nieuws\">"
$db=mysqli_connect("localhost","root","","lichtwinkel");
if(isset($_POST['update']) && !empty($_POST['update'])) {
$y = $_POST['aantal'.$_POST['update']];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '".$y."' WHERE partnr = '".$_POST['update']."'");
}
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal".$row[0]."' value='".$row[voorraad]."' /></td>";
echo "<td><input type='submit' id='update' name='update' value='".$row[0]."' /></td>";
echo "</tr>";
}
echo "</table>";
echo '</form>';
?>
After all, take care about SQL Injections. "aantal" value is user input. As the submit value can be changed.

Can't update a selected row by user

I've written this code for a user to edit one row and update it in MySQL, but it always posts the last row no matter which row you have selected (there are 3 rows).
What's the problem?
<?php include("includes/db_connection.php"); ?>
<?php
global $connection;
$sid="s5";
/**select all salesman from store 5**/
$sql ="SELECT * FROM employees WHERE e_type='Salesperson' AND store_assigned='".$sid."';";
/**get the result and put into table, which can be edited by user**/
$result = mysql_query($sql);
echo "<form method='post' action='update_salesman.php'>";
echo "<table border='1'><tr><th>Employee ID</th><th>Name</th><th>Address</th><th>Email</th><th>Job Title</th><th>Store</th><th>Salary</th></tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td><input type='text' name='eid' value='".$row['eid']."' readonly /></td>";
echo "<td><input type='text' name='e_name' value='".$row['e_name']."' /></td>";
echo "<td><input type='text' name='e_addr' value='".$row['e_addr']."' /></td>";
echo "<td><input type='text' name='e_email' value='".$row['e_email']."' /></td>";
echo "<td><input type='text' name='e_type' value='".$row['e_type']."' /></td>";
echo "<td><input type='text' name='store_assigned' value='".$row['store_assigned']."'/></td>";
echo "<td><input type='text' name='e_salary' value='".$row['e_salary']."' /></td>";
echo "<td><input type ='submit' value='update' /></td></tr>";
}
echo "</table>";
echo "</form>";
print($sql);
?>
Get the posted data, and update it in MySQL database:
<?php include("includes/db_connection.php"); ?>
<?php
$eid = $_POST['eid'];
$ename = $_POST['e_name'];
$eaddr = $_POST['e_addr'];
$eemail = $_POST['e_email'];
$etype = $_POST['e_type'];
$estore = $_POST['store_assigned'];
$esalary = $_POST['e_salary'];
$sql = "UPDATE employees SET e_name='" . $ename . "', e_addr='" . $eaddr . "', e_email='" . $eemail . "', e_type='" . $etype . "', store_assigned='" . $estore . "', e_salary='" . $esalary . "' WHERE eid='" . $eid . "' ;";
$result = mysql_query($sql);
print("</br>" . $sql);
?>
The result is always this:
UPDATE employees SET e_name='Norah ', e_addr='111 Melwood,PA', e_email='anorahm#gmiil.com', e_type='Salesperson', store_assigned='s5', e_salary='4000.00' WHERE eid='e334' ;
Your problem is twofold. First, when generating the HTML code, you use a while loop to echo the fields. Note that the names of these fields are the same every time the loop runs. (You can see this in the generated HTML (source code). Note that on submitting, one one of the multiple same-named fields will be posted.
Second, in the PHP form handler code, you read the post data and then do one update query, while you may want to update more than one field.
The easiest way to solve this is to make sure that the field names in the HTML form are different for each of the rows, and to use a loop structure when updating the sql table such that there's an update for each row.
even though it may appear fine on the html side, it's clear what's happening on the server side when it gets the form
When the server gets the form it will only see the last record because each record will overwrite the values that come before it resulting in only getting the data from the last record
What you can do is give each set of values its own form (Wouldn't suggest). But with this method, you can leave your code almost as is, just move the form tags into the while loop. OR write the input names as e_name[], etc.
This way it will be passed as an array to the server and you can loop through to get all your values
On the server end, to get the array you would do something like
$e_names = $_POST['e_name']; //Value will be an array

listing post keys to make it easier to use

I have 12 keys inside my $_post[].
I can reach them without any issue but I want to make it easier, as there will be more keys (I am thinking of 30+).
Here is an example of what I have inside my $_post:
$_post['var1']
$_post['qty1']
$_post['var2']
$_post['qty2']
$_post['var3']
$_post['qty3']
This continues till 12 (at the moment).
It is being posted this way:
$count = 0;
foreach ($results as $mat) {
$count++;
echo "<tr><td>{$count}</td>";
echo "<td><input type='text' name='var{$count}' value='{$mat['var']}' /></td>";
echo "<td><input type='text' name='qty{$count}' value='{$mat['qty']}' /></td></tr>";
}
I need to use those variables later to update my sql table, and to have it done one-by-one is a nightmare ( as I am still not sure how many it will be ).
What can I do to achieve it in an easier way ?
you can make name as array like this. var[] and qty[]
echo "<td><input type='text' name='var[]' value='{$mat['var']}' /></td>";
echo "<td><input type='text' name='qty[]' value='{$mat['qty']}' /></td></tr>";
and receive in php like this
$arr_var = $_POST['var'];
$arr_qty = $_POST['qty'];
foreach($arr_var as $key=>$value)
{
$var = $value;
$qty = $arr_qty[$key];
}
foreach($_POST as $key=>$value)
{
$$key = $value; // notice the $$, it's known as variable variable
// remove the below comment if you want to see how they are coming out
// echo "$".$key." = ". $value."<br />";
}
This will create variables names based on the name attribute of the input box.

PHP - trying to create an array of checkboxes,

I'm trying to create an Array from multiple checkboxes that are created via a while loop. the check boxes are named 'to_delete[1]', 'to_delete[2]', etc. etc.
the array statements i've tried are these:
$toDelete = array($_POST['to_delete']);
$toDelete = array($_POST['to_delete'][]);
to veryify there is an array, i go to print but find it is empty print_r($toDelete). What am i doing wrong?
the code is below. Yes, i'm doing this procedurally, and then will re-write as OOP.
big thanks for any help on this!,
$showQ = "SELECT * FROM urls";
$result = mysql_query($showQ);
$numRows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
if(!$result) {
mysql_error();
} else {
echo "<form action='".$_SERVER["PHP_SELF"]."' method='post'>";
$i=0;
while($row = mysql_fetch_array($result)) {
echo "<input type='text' class='manId' name='manId[]' value=" . $row['id'] . " />";
echo "<input type='text' class='url' name='url[]' value=" . $row['url'] . " />";
echo "<input type='checkbox' name='to_delete[" .$i. "]' /><br/>\n";
$i++;
}
echo "<input type='submit' value='delete' name='submit' />";
echo "</form>";
}
$toDelete = array($_POST['to_delete[]']);
print_r($toDelete);
Ultimately, i want to traverse the array, see which ones are checked and then delete the corresponding row from the table.
You don't want to create an array with the array() call, but rather to access one. $_POST will receive input names ending with [] as arrays, so the corresponding array keys in $_POST will already be arrays. The way you've written your code, you are assigning a one-element array containing a sub-array from $_POST. Instead, try the following:
// Test if $_POST['to_delete'] is set and non-empty
// If it's empty, create an empty array, otherwise assign it to $toDelete
$toDelete = empty($_POST['to_delete']) ? array() : $_POST['to_delete'];
print_$($toDelete);

mysql select distinct query in PHP

$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);
$row_num = mysql_num_rows($result);
$rows = mysql_fetch_array($result);
echo "<select name='Branch'>";
for($i=0;$i<=$row_num-1;$i++){
echo "<option value='".$rows[$i]."'>".$rows[$i]."</option>";
}
echo "</select>";
echo "<input type='submit' Value='submit' />";
echo "</form>";
I am trying to create a dropdown using the above code for my form. But its not working. There are 3 distinct values in the Branch column but in the dropdown, it shows only one value(the first one) and the next two as blank values.
However when in echo $row_num, its shows 3.
Thats means its fetching the three rows, but then why its not showing in the dropdown list.
If I run the same query in phpmyadmin it shows the correct answer i.r it returns 3 distinct Branch values.
You should do something like this:
$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);
echo "<select name='Branch'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
echo "</select>";
echo "<input type='submit' Value='submit' />";
echo "</form>";
you need to mysql_fetch_array() for each row. That function returns an associative array for one row only. just include it inside your for loop just above your echo statement.
edit: mysql_fetch_array() actually returns an array (by default) that has associative indices and numbered indices. You can continue using it the same way, though.
You need to loop through your query using the following:
$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);
echo "<select name='Branch'>";
while($rows = mysql_fetch_array($result)){ // should probably use mysql_fetch_assoc()
echo "<option value='".$rows['Branch']."'>".$rows['Branch']."</option>";
}
echo "</select>";
echo "<input type='submit' Value='submit' />";
echo "</form>";
mysql_fetch_array only returns the current dataset as an array, and moves the internal pointer ahead. You need to repeatedly call mysql_fetch_array to get all results.
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['Branch']."'>".$row['Branch']."</option>";
}
There is a problem in the loop using a while loop:
while($rows=mysql_fetch_array($result)){
echo "<option value='".$rows[$i]."'>".$rows[$i]."</option>";
}
Try this
What you really need is to learn how to use templates.
But it seems Stackoverflow is definitely not the place where one can learn professional ways of website developing.
get your data first
$select = $array();
$sql = "SELECT DISTINCT Branch FROM student_main";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
while($row = mysql_fetch_array($res)) $select = $row[];
And then use it in the template
<form>
<select name='Branch'>
<? foreach($select as $row): ?>
<option value="<?=htmlspecialchars($row['Branch'])?>">
<?=htmlspecialchars($row['Branch'])?>
</option>
<? endforeach ?>
</select>
<input type='submit' Value='submit' />
</form>
mysql_fetch_array will only return the first row...
see here for full details :)

Categories