So basically, I have an HTML form that asks a user to select an option from a dropdown list. The list is populated with a mysql query, but also includes an additional option labeled as 'All.' If the users selects all I want it my PHP script to run a timecard for so and so and then underneath that do the same thing for the next employee, so on and so forth. So far, it works fine if you select just one person, but if you select all it says there are no results to display :/. Any help is appreciated.
if ($empfullname == 'All') {
$query = "select fullname from ".$db_prefix."info order by fullname asc";
$result = mysql_query($query);
} else {
print timecard_html($empfullname, $local_timestamp_in_week);
}
while ($row=mysql_fetch_array($result)) {
print timecard_html(stripslashes("".$row['empfullname'].""), $local_timestamp_in_week);
}
Also, I know mysql is depreciated, but that is what I know and I am just trying to make it work with this. Thanks.
Now, something looks off in your code. When doing your select statement, you are selecting 'fullname'. But when printing, you are using 'empfullname'. Kindly correct this first.
Related
I have written the following code to generate information from an SQL database:
<?php
$search1 = "SELECT Name FROM users";
if($mysqli->query($search1) == TRUE)
{
echo "You have successfully searched the request";
}
$result = $mysqli->query("SELECT Name FROM users");
echo '<table border=1px>';
echo'<th>Name</th>';
echo $row;
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo'<tr>'; // printing table row
echo '<td>'.$row['Name'].'</td>';
echo'</tr>';
}
echo '</table>';
?>
This generates a list of names in the table. There are other columns in the table such as Country, Email, Hobby and Date Signed up. All of which are VARCHAR except the last which is of type DATE. I am trying to figure out code so that when I click on one of the generated names, the rest of the information (Country, Email etc,) is shown.
Just doing something like:
echo '<td><a href=\"userinfo.php?username='.$row['Name'].'\">'.$row['Name'].'</td>';
And then in userinfo.php, read the $_GET['username'] parameter to make a query similar to the one you have above, something like this:
$search1 = "SELECT * FROM users where Name=?";
And then setting the parameter $_GET['username'] to the prepared statement (if you want to avoid MySQL injections).
You can use the following SQL to get only the information that will be used in your listing page, in your case that would be identifier and name columns (you have identifier column, right? if not, check again your database structure - there's something wrong).
SELECT ID, Name FROM `users`
And then you can create extra page in your application, e.g. show.php where you will pass the identifier of each record as $_GET parameter, e.g. show.php?id=5
And there you should create another query:
SELECT * FROM `users` WHERE `ID` = $_GET['id']; /* that's not secure, read below */
Once you have that data, you can list it and you're done.
If you want to create one-page application, you can hide available info with CSS and display it when user clicks on username. Read about jQuery. You can even use AJAX. It's your choice.
If you want to make everything better, you can try use PDO.
Also, be aware of these vulnerabilities:
SQL Injections
Cross-site scripting
I'll admit, I don't know tons about MySQL queries or JSON for that matter but I would like to. Currently when I get data from my database I query one table which brings values into another query and so on. I don't think this is the best practice to go about receiving all the data I need to display. Below is an example of how my MySQL queries currently work in a PHP foreach function:
So, is there a better way of completing the query(s) I want and how would I be able to encode it as JSON?
Any help would be appreciated, thank you.
From what I understand, your code is doing something like this:
<?php
$friends = query("SELECT Friends");
while($row = fetch_object($friends)){
$friend_dets = query("SELECT Friend_dets WHERE Friend_ID = $row->Friend_ID");
$output[] = fetch_assoc($friend_dets);
}
echo json_encode($output);
?>
With this, you're making the process more complex than it needs to be. You can get all of the information you need with one query with a JOIN like this:
SELECT Name, Status, WhateverElseYouWant
FROM Friends
JOIN Profiles ON (Friends.friend-profile-id = Profiles.profile-id)
WHERE Friends.profile-id = MyCurrentProfileID
That will give you the name, status and whatever else of everyone who is friends with MyCurrentProfileID. Then, you just need to put the result in an array and json_encode it:
<?php
$friends = query($QueryFromAbove);
while($row = fetch_object($friends)){
$output[] = fetch_assoc($friend_dets);
}
echo json_encode($output);
?>
You can make 1 SQL query for this list, can you tell me whats your table Friends and Profiles info.
In Friends table you must have id to profiles to indicate is the friens of what profile.
The query may be like : select profile.* from profile, friends, where friends.id_profile = profile.id and profile.id = current-profile-id
In your graph you use current profile id in friends table and not profile this may be error
I have a PHP results page which starts off "first-pass" with ALL rows returned. It's a search listing of all pizza places in the county.
SELECT * from pizzeria;
Then the user can drill down into more detail... the page also has a CSS dropdown menu where the user can pick a specific neighborhood (which carries a URL):
href="samepage.php?neighborhood=HELLSKITCHEN"
which then changes the query after I pick up the $_GET[]
SELECT * from pizzaria WHERE nbh=(the $_GET[] variable sent in the URL);
but I'd like the page to call itself and I have header("Cache-Control:no-cache"); at the top.
I'm trying to create a first-pass or first visit flag variable with the isnull() function:
if (is_null($firstpass)) {
$query = SELECT all the records from the pizzaria table
} else {
$query = SELECT only the records WHERE I $_GET[] the value from the reloaded URL
}
It seems though that the $firstpass variable doesn't stick on reloads. Should I SESSION that variable? (though still have the problem of constantly resetting it)
Or maybe implement some other approach?
I know I can redirect to a separate second page and javascript back to this page to avoid "headers already sent", but I want to avoid the round-trip back to the client.
Is there a known best practice on reloads with new info? Kinda new to PHP here. thanks
Maybe I didn't understand well your problem but why wouldn't you do :
if (!isset($_GET['example'])) {
$query = 'SELECT * FROM pizzerias';
} else {
$query = 'SELECT * FROM pizzerias WHERE pizzeria = \'.mysql_real_escape_string($_GET['example']).\' LIMIT 1';
}
at the first pass because, it seem that the $_GET variable is set only when the user choose a pizzeria?
Here is a more targeted answer.
NOTICE: mysql_* functions are being depreciated, so use PDO instead. In my example I'm being semi-lazy and not using PDO.
//Connect to database and define table up here
...
if(!isset($_GET['neighborhood')){
$q = "SELECT * FROM pizzeria;";
}else{
$q = sprintf("SELECT * FROM pizzeria WHERE nbh=%s",mysql_real_escape_string($_GET['neighborhood']));
}
$query = mysql_query($q);
foreach($row = mysql_fetch_array($query,MYSQL_ASSOC){
//display the updated view of restaurants.
}
I would also suggest that you use jQuery for that Web 2.0 effect. It's really nice when you select from a drop-down menu and things magically move without a page reload.
I'm really struggling to get my code to work, and I can't figure out why.
I have a database in my PHPMyAdmin and it contains 2 tables:
tennisCourts
courtID
courtName
bookingFee
tenniscourts_Availability
courtID
court_dateBooked
I am writing a PHP program using PEAR repository, and I am struggling to create code that allows me to:
Display All courtNames and their corresponding bookingFee BASED ON users search date ONLY IF the courtName is not already booked by another user.
Here is my current code:-
$CHOSEN_BOOKING_DATE = $_GET['user_dateField']; //GET's input data from user form in my other html document.
$database->setFetchMode(MDB2_FETCHMODE_ASSOC);
$myQuery = "SELECT * FROM tennisCourts, tenniscourts_Availability WHERE court_dateBooked != $CHOSEN_BOOKING_DATE";
$queryResult =& $db->query($myQuery);
if (PEAR::isError($queryResult)) {
die($queryResult->getMessage());
}
echo '<table>';
while ($Col =& $queryResult->fetchRow()) {
echo '<td>'.$queryResult['courtName'].'</td>';
echo '<td>'.$queryResult['bookingFee'].'</td>';
echo '<td>'.$queryResult['court_dateBooked'].'</td>';
}
?>
The code above displays all the courtNames and BookingFee's for All court_dateBooked fields in my database. I cant get it to display the courtNames and bookingFee only if it isn't booked. If it is booked it should return "sorry no courts found on this date".
I am still new to PHP and SQL so forgive me if I have not made myself clear. I have been researching online and various sources say to use SQL UNION OR JOIN? Could someone please enlighten me on how they could be used in context to my scenario? I really appreciate any help. Thank you for checking out my question.
Try this:
$myQuery = "
SELECT c.courtName
, c.bookingFee
, a.court_dateBooked
FROM tennisCourts AS c
LEFT JOIN tenniscourts_Availability AS a ON c.id = a.courtID
WHERE a.court_dateBooked != '" . $CHOSEN_BOOKING_DATE ."'";
Make sure you sanitize and escape $CHOSEN_BOOKING_DATE properly before executing your query. Since it looks like you're using PDO you should be using prepared statements for this.
I wonder whether someone may be able to help.
I posted a similar message to this little three days ago, but I think that my explanation of the problem wasn't particualrly good so I thought I'd start afresh. I will say that I am new to programming in PHP so please bear with me.
I have three mySQL tables, 'userdetails', 'detectors' and 'detectorsearchheads' with the following fields:
userdetails
userid
name
detectors
userid
detectorid
detectordescription
detectorsearchheads
userid
detectorid
detectorsearchheadid
detectorsearchheaddescription
What I would like is to have a drop down menu on my HTML form that through PHP, shows the list of detectors applicable to the user that is logged on. In turn I would then like another drop down menu that again is user specifc, but additionally only shows the detector search heads applicable to the value selected from the first drop down menu.
I appreciate that there may be other ways to do this but I am more comfortable with PHP.
I just wondered whether someone could possibly please show me what I need to do to get this to work. As I said earlier I am fairly new to PHP, so the simpler the better.
Many thanks and regards
Chris
UPDATED CODE
<?php
mysql_connect("hostname", "username", "password") or die("Connection Failed");
mysql_select_db("databasename")or die("Connection Failed");
$query = "SELECT * FROM detectors WHERE `userid` = '1' ORDER BY 'detectorname' ASC";
$result = mysql_query($query);
?>
<select name="detectorname">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['detectorname'];?>"> <?php echo $line['detectorname'];?> </option>
<?php
}
?>
</select>
Check this tutorial for example.
Before that you have to generate the html and js code with php. Basicly, get the data from database, and generate needed list. For example:
echo "<li>".$dataFromDatabase."</li>";
You will need CSS/JS to display the Drop Down Menu. With PHP you will prepare the text to be displayed.
After the mysql query, the result should be echoed in appropriate format.
For Eg. if your CSS displays list items(li) as menu, you need to do what 'Waltsu' said.
$result = mysql_query("..."); //your specific query
while ($row = mysql_fetch_assoc($result))
{
echo '<li>'.$row['detectordescription'].'</li>';
//so on
}