First record from database is not displayed? - php

Trying to work on a clients site and I am having a bit of difficulty. When I have no entries in the database, it catches at if(!row) and displays the message. This part works fine. My issue is when I have entries in the db, they do not display. I know the while loop works because I have several pages running a similar loop. In fact, this loop was copied from another page that displays this entry's information on a public page.
I know this site is mainly for questions, but I think I just need a fresh pair of eyes to look at my code(I've been coding for over 12 hours and I'm a bit tired). A lot of the code below is from a previous web designer and if it were up to me, I would just rewrite the entire site because the code is "out of date", but the client just wants me to improve on it. Any help would be greatly apprecieated.
$row = mysql_fetch_array($result);
if (!$row) {
echo '<tr><td bgcolor="ffffff" colspan="3"><font face="arial,helvetica" size="2" color="000000">There are no entries at this time, check back later.</font></td></tr>';
} else {
while ($row = mysql_fetch_array($result)) {
echo '<tr>
<td bgcolor="ffffff"><font face="arial,helvetica" size="2" color="000000">$date - $row["theme"]</font></td>
<td bgcolor="ffffff" align="center">
<form action="dsp_modifyposition.php">
<input type="hidden" name="specialID" value="$row["specialID"]">
<input type="hidden" name="theme" value="$row["theme"]">
<input type="submit" value=" Modify ">
</form>
</td>
<td bgcolor="ffffff" align="center">
<form action="act_deleteposition.php" onsubmit="return confirm(\'Are you sure you want to delete this event: $date \')">
<input type="hidden" name="specialID" value="$row["specialID"]">
<input type="hidden" name="theme" value="$row["theme"]">
<input type="submit" value=" Delete ">
</form>
</td>
</tr>';
}
}

When you call mysql_fetch_array for the first time, the mysql result pointer is moved to the next row. Because nothing is done with this row, this first row does not get displayed. What you want is mysql_num_rows to check how many rows are in the resultset. As a side-note, I would suggest using mysql_fetch_assoc if you're not using the numeric indices.
if (!mysql_num_rows($result)) {
echo '...';
} else {
while ($row = mysql_fetch_assoc($result)) {
echo '...';
}
}

Change your first lines to this:
$cnt = mysql_num_rows($result)
if (!$cnt) {
echo '<tr><td bgcolor="ffffff" colspan="3"><font face="arial,helvetica" size="2" color="000000">There are no entries at this time, check back later.</font></td></tr>';
} else {
....

Your if() statement seems flawed. The statement:
$row = mysql_fetch_array($result);
will fetch a row and move the pointer in $result to the next row, so your while will start at the second row. If your query returns only one row, you're effectively calling mysql_fetch_array() twice and skipping over the data returned.
You should find some other way of checking if you have results (possibly with mysql_num_rows()).

Related

Deleting Specific rows using PHP

I am trying to add a delete button to my note taking website project I am doing at school. Almost like a forum, where you would delete replies to a topic... I want to be able to delete individual notes. Currently I can delete, however it will only delete the most recent note (bottom of the notes table). How would I get it so the delete button deletes the note from the corresponding row, not just the bottom one.
The main interface (Where I believe the problem is)
$sql="SELECT noteID, title, note, timestamp FROM $tbl_name WHERE user='$currentuser' AND subject='$currentsubject'";
$result=mysql_query($sql);
?>
<table align="center" id="notes">
<tr>
<td width="10%"><strong>Title</strong></td>
<td width="10%"><strong>ID</strong></td>
<td width="50%"><strong>Note</strong></td>
<td width="10%"><strong>Time</strong></td>
<td width="10%"><strong>Delete</strong></td>
</tr>
<?php
// Start looping table row
while($rows=mysql_fetch_array($result)){
echo'
<br>
<tr>
<td>'.$rows['title'].'</td>
<td>'.$rows['noteID'].'</td>
<td>'.$rows['note'].'</td>
<td>'.$rows['timestamp'].'</td> ';
$todelete = $rows['noteID'];
$_SESSION['todelete'] = $todelete;
echo'
<td><form method="post" action="deletenote.php" ><input type="submit" name="submit" value="Delete" </td>
</tr>
';
}
ob_end_flush()
?>
Another way of doing it would be by just providing a delete link for each post:
// Start looping table row
while($rows=mysql_fetch_array($result)){
echo '<br>';
echo '<tr>';
echo '<td>'.$rows['title'].'</td>';
echo '<td>'.$rows['noteID'].'</td>';
echo '<td>'.$rows['note'].'</td>';
echo '<td>'.$rows['timestamp'].'</td>';
echo '<td>Delete</td>';
echo '</tr>';
}
Keep in mind that deletenote.php would have to verify that the user is signed in and has permission to delete the post.
First of all: where is your corresponding code/query regarding the specific use case (delete note)?
You are trying to submit a form without any parameters, I am assuming you are trying to use the session variable. However, this variable will always be set to the last loop-iteration. Therefore, I would recommend you to use this code sample:
// Start looping table row
while($rows=mysql_fetch_array($result)){
echo '<br>';
echo '<tr>';
echo '<td>'.$rows['title'].'</td>';
echo '<td>'.$rows['noteID'].'</td>';
echo '<td>'.$rows['note'].'</td>';
echo '<td>'.$rows['timestamp'].'</td>';
echo '<td><form method="post" action="deletenote.php" ><input type="hidden" name="noteID" value="'.$rows['noteID'].'"><input type="submit" name="submit" value="Delete"></form> </td>';
echo '</tr>';
}

only can insertes last row data of table into session

Here is my code
<?php
$count = 1;
$sql = "SELECT * FROM `scheduledata`
WHERE `departdate` = '$departdatephp'
AND `orginplace_id` = '$orginplacephp'
AND `desplace_id` = '$desplacephp' ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<th><?php echo $count;?></th>
<th><?php echo $row["departtime"];?><input type="hidden" name="departtime" value="<?php echo $row['departtime'];?>" method="post"></th>
<th><?php echo $row["returntime"];?><input type="hidden" name="returntime" value="<?php echo $row['returntime'];?>" method="post"></th>
<th><?php echo $row["adultprice"]; ?>MYR<input type="hidden" name="adultprice" value="<?php echo $row['adultprice'];?>" method="post"></th>
<th><?php echo $row['schedule_id'];?><input type="hidden" name="scheduleid" value="<?php echo $row['schedule_id'];?>" method="post"></th>
<th><?php echo $row['flight_id'];?><input type="hidden" name="flightid" value="<?php echo $row['flight_id'];?>" method="post"></th>
<th><button type="submit" class="submit-button" method="post" name="departbtn[]">booking</button></th>
<?php
$count = $count+1;}
?>
</tr>
Lest says i had 3 choice of booking like this
3 booking button
Here is my output code
<?php
if(isset($_POST['departbtn']))
{
$departtimephp = $_POST['departtime'];
$returntimephp = $_POST['returntime'];
$price = $_POST['adultprice'];
$scheduleid = $_POST['scheduleid'];
$flightid = $_POST['flightid'];
$_SESSION['departtime'] = $departtimephp ;
$_SESSION['returntime'] = $returntimephp ;
$_SESSION['adultprice'] = $price ;
$_SESSION['scheduleid'] = $scheduleid ;
$_SESSION['flightid']= $flightid ;
print_r($_SESSION['departtime']);
print_r($_SESSION['returntime']);
print_r($_SESSION['adultprice']);
print_r($_SESSION['scheduleid']);
print_r($_SESSION['flightid']);
}
?>
No matter which choice I select, the out put is always the last row of table, I guess its because there all had same variable name so system direct insert last row data.
My problem is a bit same like here, they suggest using array[] to solve this but I got error when i add a foreach inside a isset, so any idea how to get the correct data?
Appreciate for any solution.
The code shown doesn't explicitly show this, but I strongly suspect that the entire table is your form. Which means that no matter which button you click, all values are being submitted.
For starters, the browser wouldn't know which one you "meant" and any given value would just overwrite the previous one in the form POST. (Which explains the behavior you're seeing... you always get the last record.) But, aside from that... Why? Why submit all of the data when you really just need a single identifier of the record which was selected?
For each row in the table, put an entire self-contained form. Something like this:
<tr>
<!--- your other table cells --->
<th>
<form method="post" action="someAction.php">
<input type="hidden" name="flightid" value="<?php echo $row['flight_id'];?>" />
<button type="submit" class="submit-button" method="post" name="departbtn">booking</button>
</form>
</th>
</tr>
(You can put more of those hidden form fields there, as many as you like really. Though honestly you should just need an identifier. The server already has the rest of the data. And the more fields you use is just more opportunities for users to mess with the system.)
That way when you click a button, there's no ambiguity on the option being selected. Each form is entirely self-contained and has only the data it needs to post.

Sending a SQL command with one click of an HTML button through PHP

So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.

Deleting multiple records(rows) from tables using checkboxes

Trying to delete multiple rows using check-boxes. At first i'm generating table of contents with checkbox column. Then posting data to php side. The problem is, php side returning back to the current page. It means that all done successfully and page returned user back. But no success. There is no error in php logs, and MySQL problem. I tried print_r ($_POST['checkbox']); die(); after $delete=$_POST['delete'];. It gave me result something like that Array ( [0] => on [1] => on ) what's wrong with my code?
My HTML markup looks like that
<?php
$result = $db->query("SELECT id, name, showinmenu FROM menu") ;
$num=$result->num_rows;
if ($num>0) {
?>
<form method="post" action="processor/dbdel.php">
<div style="overflow-y: auto; overflow-x: hidden; height:500px">
<table id="list" class="features-table">
<thead>
<tr>
<th>#</th>
<th style="min-width:80px;" class="name">Ad (menyuda işlənən)</th>
<th>Sil</th>
</tr>
</thead>
<tbody>
<?
while ($row = $result->fetch_object()) {
echo '<tr>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td><input type="checkbox" name="checkbox[]" method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
</tr>';
}
// when the loop is complete, close off the list.
echo "</tbody> <tr id='noresults'>
<td style='text-align:center' colspan='9'>Nəticə yoxdur</td>
</tr></table>
</div>
<p style='text-align:center;'>
<input id='delete' type='submit' name='delete' value='Seçilənləri sil'/> </p>
</form>";
}
?>
And here is my PHP code
<?php
require '../../core/includes/common.php';
$delete=$_POST['delete'];
if($delete) // from button name="delete"
{
if (is_array($_POST['checkbox']))
foreach($_POST['checkbox'] as $del_id) {
$del_id = (int)$del_id;
$result=$db->query ("DELETE FROM menu WHERE id = '$del_id'") or die($db->error);
$result2=$db->query ("DELETE FROM pages WHERE id = '$del_id'") or die($db->error);
}
if($result2)
{
header("location:".$wsurl."admin/?page=db");
}
else
{
echo "Error: ".$db->error;
}
}
?>
Your code is an absolute disaster.
1) Using echo with repeated string concatenation to output html. Look up HEREDOCs, double-quoted strings, or simply breaking out of PHP-mode (?>) to output html.
2) Checking for POST by looking for form fields. If you want to make sure you're in a POST situation, then do if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... } instead. This is 100% reliable, and does not depend on the presence (or absence) of particular form fields. If the data was submitted via post, this statement will evaluate to true, ALWAYS.
3) You are blindly embedding user-provided data into SQL query strings. Read up about SQL injection attacks, then consider what happens if someone hacks your form and submits a checkbox value of ' or 1' - say goodbye to the contents of your checkbox table.
4) You appear to have a stray " in your checkbox output line:
[...snip...] method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
^--here
which is almost certainly "breaking" your form and causing subsequent tag attributes to be misinterpreted.
5) on the plus side, I'll have to give you this much - you are at least checking for query errors on your two delete queries, which is always nice to see. However, that's a minor plus in a huge field of negatives.

How do I post back to a database?

I am new to PhP and MySQL and now having trouble displaying certain records. I have records pf list of students and their year level stored in a database. I was able to display all of them in a webpage. Now I have one textbox and a button and what I wanted to do is when I enter for example "1" on the textbox and click the button, what will appear on my page will be the records of all the first year students only.
Somehow I need to change it so that when the year is posted back then it changes the sql to limit the information displayed.
Any suggestions or links to some examples will be much appreciated. Here is my code.
<form name="form1" method="post" action="">
<div align="center">
<?php
include("dbcon.php");
$query="select * from student order by year, studname";
$result=#mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)>0)
{
?>
<label>
<input type="text" name="txtyear" id="txtyear">
<input type="submit" name="btnyear" id="btnyear" value="Submit">
</label>
<table width="75%" border="1">
<tr>
<td align="center" width="20%"><strong>Student Number</strong></td>
<td align="center" width="27%"><strong>Name</strong></td>
<td align="center" width="23%"><strong>Course</strong></td>
<td align="center" width="30%"><strong>Year Level</strong></td>
</tr>
<?php
while($row=mysql_fetch_array($result))
{echo "<tr>";
echo "<td>".$row['studno']."</td>";
echo "<td>".$row['studname']."</td>";
echo "<td>".$row['course']."</td>";
echo "<td>".$row['year']."</td>";
echo "</tr>";
}
?>
</table>
<?php
}
else
echo "no records found";
?>
</div>
</form>
You need a WHERE clause. A very basic example might look like this:
$year = mysql_real_escape_string($_POST['year']);
$query = SELECT * FROM student WHERE year = $year ORDER BY studname";
NB: Look into the PHP MySQLi extension. These functions are almost identical to their mysql equivalent, but come with numerous improvements.
Also, you would likely want to improve the validation of the $_POST['year'] field. Ensuring that it is an integer with is_int() wouldn't be a bad idea. You could also typecast it with (int) like (int) $year = mysql_real_escape_string($_POST['year']); and then perform the query if the year isn't 0. Perhaps you know all this already... or perhaps I'm getting ahead of myself. Either way, I'll stop. :)
You can find more info about Mysql select query syntax on
http://dev.mysql.com/doc/refman/5.1/en/select.html.
Also don't use # for errors suppression in php-code. Because of it will slow your script. Try to process such situation manually. In this case (#mysql_query($query)) it seems it doesn't make sense anyway.

Categories