I currently have a page where it displays data from my database in tables and it also searchable using some key terms. What I want to do is for the table to be hidden unless it is being searched. I have rephrased my codes because this is an assignment and i dont want it to be picked up as plagiarism. I really hope someone knows a way to do this
<?php
include_once('connection.php');
$SQL = "SELECT * FROM `players`";
if (isset($_POST['search'])) {
$search_word = mysql_real_escape_string($_POST['search_bar']);
$SQL .= " WHERE player_id LIKE '%{$search_word}%'";
$SQL .= " or player_name LIKE '%{$search_word}%'";
}
$SQL .= 'group by player_id, player_name order by player_id ASC';
if( !( $SQLRes = mysql_query( $SQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
if( mysql_num_rows( $SQLRes )==0 ){
echo '<tr><td colspan="1">No results </td></tr>';
}else{
$current_player_id = false;
while( $row = mysql_fetch_assoc( $SQLRes ) ){
if ($row['player_id'] !=$current_player_id) {
if ($current_player_id !== false)
echo '</table>';
echo '
<h4>'.$row['player_id'].'</h4>
<table style = "width: 100%" class="listing" cellpadding="0" cellspacing="0">
<tr>
<th style="width: 50%">Player Name</th>
</tr>';
$current_player_id = $row['player_id'];
}
echo '<tr>
<td>'.$row['player_name'].'</td>
<td><a href =delete.php?del='.$row['player_id'].'><strong>DELETE<strong/></a></td>
</tr> ';
}
}
echo '</table>';
?>
</table>
At the start you open with an if statement:
if (isset($_POST['search'])) {
$search_word = mysql_real_escape_string($_POST['search_bar']);
$SQL .= " WHERE player_id LIKE '%{$search_word}%'";
$SQL .= " or player_name LIKE '%{$search_word}%'";
}
It looks to me like the check for the $_POST variable is telling you if you have a search.
That if just needs to wrap the whole of this body of code and it should do what you're looking for.
That said, there are a few niggles elsewhere in your code - please take these the right way - in an effort to help and guide...
1 - Rather than build your "like" statements in your SQL, take a look at bind variables. Also, take a look at mysqli usage examples.
2 - Rather than echoing through your code, consider building an $html string up and then echoing at the end.
3 - It looks like you're coding for your SQL select to return multiple instances of the same player. That suggests either a flaw in the datamodel (the table is called player after all), or in the SELECT - why not get back distinct rows.
4 - Echoing SQL errors back to the console is a great way to give external people access to protected information about your system. Consider logging to a file instead - at least in production.
5 - I've corrected your indentation. Learn how to use it, it will save your brain many times over if you indent code properly.
Related
I have a database where teams will have multiple entries each with different locations. Each entry will have a team name. So for example, team1 might appear several times but each time the location will be different.
The structure of the DB is (each of these represents a column header):
team_name, first_name, last_name, location, arrival_time
My current working code creates HTML tables grouped by team name but currently only creates one row to show the first location and the time of arrival for the first location. I need this to dynamically create more rows to show all locations and arrival times for each team.
The desired result would look like this -
https://codepen.io/TheBigFolorn/pen/LqJeXr
But current result looks like this -
https://codepen.io/TheBigFolorn/pen/qgMppx
And here is an example of how the DB table might look -
https://codepen.io/TheBigFolorn/pen/daqJze
I've tried breaking up the echo and adding a second while loop before the row that I want to apply the above logic to but it seems to break everything. Any input on how I get this to work without having to use separate queries for each team would be very much appreciated. I'm new to php so please go easy on me :)
<?php
$leaders = "SELECT *, COUNT(location) FROM my_example_table GROUP BY team_name";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='red-border'>
<h2>". $row["team_name"]. "<br><small>Total locations visited: ". $row["COUNT(location)"]. "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>
<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>
</table>
</div>
";
}
} else {
echo "0 results";
}
?>
Your problem is due to the GROUP BY, as you've probably realised. This is necessary in order to get a count per team, but causes the number of rows output to be only 1 per team - that's what grouping does. Fundamentally, running an aggregate query such as a COUNT or SUM is incompatible with also outputting all of the row data at the same time. You either do one or the other.
Now, you could run two queries - one to get the counts, and one to get all the rows. But actually you don't really need to. If you just select all the rows, then the count-per-team is implicit in your data. Since you're going to need to loop through them all anyway to output them in the HTML, you might as well use that process to keep track of how many rows you've got per team as you go along, and create the "Total number of locations" headings in your HTML based on that.
Two things are key to this:
1) Making the query output the data in a useful order:
SELECT * FROM my_example_table Order By team_name, arrival_time;
2) Not immediately echoing HTML to the page as soon as you get to a table row. Instead, put HTML snippets into variables which you can populate at different times in the process (since you won't know the total locations per team until you've looped all the rows for that team), and then string them all together at a later point to get the final output:
$leaders = "SELECT * FROM my_example_table Order By team_name, arrival_time;";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
$currentTeam = "";
$locationCount = 0;
$html = "";
$teamHtmlStart = "";
$teamHtmlEnd = "";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
//run this bit if we've detected a new team
if ($currentTeam != $row["team_name"]) {
//finalise the previous team's html and append it to the main output
if ($currentTeam != "") $html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
//reset all the team-specific variables
$currentTeam = $row["team_name"];
$teamHtmlStart = "<div class='red-border'><h2>".$currentTeam."<br><small>Total locations visited: ";
$locationCount = 0;
$teamHtmlEnd = "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>";
}
$teamHtmlEnd .= "<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>";
$locationCount++;
}
//for the final team (since the loop won't go back to the start):
$html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
echo $html;
}
else {
echo "0 results";
}
Here's a runnable demo (using some static data in place of the SQL query): http://sandbox.onlinephpfunctions.com/code/2f52c1d7ec242f674eaca5619cc7b9325295c0d4
I'm learning this new langage PHP in order to develop modules from this software : Dolibarr
It's the first time I'm using PHP and I don't overcome to display query result in my view.
I would like to know if I wrote something wrong in my script because I don't understand all up to now. I would like to display the number of users in my software. I have to query my llx_user table and display the result in my array.
This is the part of my code :
/*
* View
*/
//Display number of users
$sql = "SELECT COUNT(u.rowid) as total";
$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
$result = $db->query($sql);
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").'</th></tr>';
if (! empty($conf->user->enabled))
{
$statUsers = '<tr class="oddeven">';
$statUsers.= '<td>'.$langs->trans("Number of Users").'</td><td align="right">'.round($result).'</td>';
$statUsers.= "</tr>";
}
$total=0;
if ($entity == '0')
{
print $statUsers;
$total=round($result);
}
print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td align="right">';
print $total;
print '</td></tr>';
print '</table>';
print '</div></div></div>';
llxFooter();
$db->close();
As I said, it's the first time I'm handling php file and I began to learn php 3 hours ago.
This is what I got :
If I comment like this :
$total=0;
//if ($entity == '0')
//{
print $statUsers;
$total=round($result);
//}
I'm getting this :
But I have 2 users in my table :
Thank you if you could help me
You're doing a good job for that you just started with PHP. Anyway, there's a little mistake in your code.
You actually query the database, but you don't fetch the result.
You have to do the following after your query:
$row = $result->fetch_row();
print $row[0]; // $row[0] will contain the value you're looking for
Also it seems that your $entity is not equal to 0. I don't see you initializing this variable anywhere, are you sure you have defined it? May you want to show us some mor of your code..
When I click on any link it opens all movies in my database. I want only that movie which begins with that letter and I don't know where I've made a mistake. Here is my code:
$azRange = range('A', 'Z');
foreach ($azRange as $letter){
echo ''.$letter.' | ';
}
if(isset($_GET["task"]) && $_GET["task"] == "view"){
$naslov = $_GET['naslov'];
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
$result = mysql_query($query)
or die ('SQL Greska: '.mysql_error());
if($result){
while($filmovi = mysql_fetch_array($result)){
echo '<center><b>';
echo '<td><img src="img/'.$filmovi["slika"].'" border="0" width="100" /></td>';
echo '</br>';
echo '<td>'.$filmovi["naslov"].'</td>';
echo '<td> ('.$filmovi["godina"].')</td>';
echo '<br>';
echo '<td>Trajanje: '.$filmovi["trajanje"].' min</td>';
echo '</b></center>';
echo '</tr>';
}
You are not passing the letter to the database query at any point.
$query =
"SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE naslov LIKE '$naslov%'
ORDER BY naslov";
Your query
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
is fetching all the movies from the database. There is no filtering here. Add some where conditions to this query and you'll get the expected result.
Changing to this query might help:
SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE `naslov` LIKE '{$naslov}%'
ORDER BY naslov
Since others have already answered your question (missing WHERE clause), I just want to mention that the <center> HTML tag is deprecated, and you should use CSS instead.
The mysql driver for PHP is also outdated, so instead of using:
mysql_query($query);
you should use
mysqli_query($link, $query);
for better security, OOP support, prepared statements, and transactions.
You can read about it here
Even if you are a beginner and you don't care about what those features mean, you should try and get into the habit of using mysqli anyway, so that when the day comes that you learn to appreciate it, you don't have to go back and update all of your code.
I have a form that searches a MySQL database using PHP. Currently, when a user inputs a search into one of two fields, the entire contents of the database are displayed. Also, if the user leaves both fields blank, again, the entire contents of the database will be displayed.
However, if the user inputs random information into both of the fields, then the results page will be blank.
The assumed usage of this form is that the user can search for an article based on the article's title, the article's author or organization, or the article's title and its author or organization by either filling out one or both of the fields.
What I'm trying to figure out is:
Why the results page keeps displaying all of the database contents.
and
How to ensure that the database is actually being queried rather than just being dumped by a coding error.
Code follows below:
search.php:
<div class="content">
<form id="form1" name="form1" method="post" action="searchdb.php">
<table width="100%" border="0" cellpadding="6">
<tr>
<td width="29%" align="right">Article Title:</td>
<td width="71%" align="left"><input name="articletitle" type="text" id="articletitle" size="50" /></td>
</tr>
<tr>
<td align="right">Author or Organization:</td>
<td align="left"><input name="articleorganization" type="text" id="articleorganization" size="50" /></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="6">
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
searchdb.php
<?php
include('settings.php');
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
while ($row = mysql_fetch_array($sql)){
echo '<br/> Article Title: '.$row['articletitle'];
echo '<br/> Article Organization: '.$row['articleorganization'];
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>View Full Entry</td>';
echo '<br/><br/>';
}
?>
When both are blank, your query states:
WHERE field LIKE '%%'
which matches everything.
The same happens when either one is blank, because you are using an OR to join the where clauses.
You can prevent this from happening, by checking the inputs aren't blank:
<?php
if (!((empty($_POST['field1']) || empty($_POST['field2']))) {
//run your query
}
Following on the post by #sberry.
if (isset($_POST['articletitle']) && $_POST['articletitle'] != "")
The variable can be set, but still be an empty string.
The method used by #xbonez is simpler as
if (!empty($_POST['articletitle'])) is the same as the above example that requires two tests
Have you tried xbonez method?
To be complete, this checks that at least one of the fields has been filled in:
if (!empty($_POST['articletitle']) || !empty($_POST['articleorganization'])) {
$query = "SELECT * from `articles` WHERE ";
$query .= "`articletitle` LIKE '%" . mysql_real_escape_string($_POST['articletitle']) . "%' ";
$query .= "OR `articleorganization` LIKE '%" . mysql_real_escape_string($_POST['articleorganization']) . "%'";
$sql = mysql_query($query);
} else {
// No results
}
Things that will only be used if one of the fields is filled in like:
$query = "SELECT * from `articles` WHERE ";
are placed inside the the if() statement, otherwise they are being parsed unneccesarily.
No need to create an array and then convert it into a string. ".=" will concatenate the string fragments into the final query string.
Matters of personal preference:
MySql keywords written in full caps, I find it makes the statements easier to read.
There are numerous discussions about it.
Search for "sql uppercase keywords style"
Using backticks around table and fieldnames:
Allows the use of reserved keywords for table or fieldnames (count, case, default, div, index, key, limit, option, order, etc...).
Reduces work for the mysql parser, it doesn't need to check whether there is a reserved word conflict.
Avoids problems if your table or field name becomes a reserved keyword in the future.
Again, numerous discussions. Search for "mysql backtick"
MySQLdocumentation:
9.3. Reserved Words
9.2. Schema Object Names
Look for "quoted identifier" on this page.
Also, if you might be migrating to a different database app in the future , you could use double quotes instead of backticks, look for "ANSI_QUOTES".
9.2.4. Function Name Parsing and Resolution
Look for "quoted identifier" on this page.
Tested this, and it should do exactly what you want.
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
EDIT
It appears your form is passing empty values, so instead of checking isset, check !empty. I have updated the code above.
I'm trying to code a basic messaging system for my website. I have the sending and reciving set up, but for some reason on the inbox the html just stops displaying. It displays halfway through the page and then just stops for some reason. Won't even display basic html like if I typed Hello it wouldn't show up. I'm confused as this has never happened before.
</table>
<p>Hello</p><!--THIS WILL DISPLAY-->
<?php
///////////End take away///////////////////////
// SQL to gather their entire PM list
include_once ('../../mysql_server/connect_to_mysql.php');
$sql = mysql_query("SELECT * FROM messaging WHERE to_id='$my_id' AND recipientDelete='0' ORDER BY id DESC LIMIT 100");
while($row = mysql_fetch_array($sql)){
$date = strftime("%b %d, %Y",strtotime($row['time_sent']));
if($row['opened'] == "0"){
$textWeight = 'msgDefault';
} else {
$textWeight = 'msgRead';
}
$fr_id = $row['from_id'];
// SQL - Collect username for sender inside loop
$ret = mysql_query("SELECT * FROM myMembers WHERE id='$fr_id' LIMIT 1");
while($raw = mysql_fetch_array($ret)){ $Sid = $raw['id']; $Sname = $raw['firstname']; }
?>
<p>Hello</p><!--THIS WON'T DISPLAY-->
<table width="96%" border="0" align="center" cellpadding="4">
Any help is appreciated..
EDIT:
The first while loop does close, just after the table. Everything outside the first while loop displays, however, everything inside the while loop doesn't.
Don't know if this is just a cut and paste error, but your first while loop doesn't look closed. Try closing it and see where it goes from there.
while($row = mysql_fetch_array($sql)){ //needs closing
EDIT:
Have you tried to see if your sql is throwing any errors:
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
This PHP link might be useful.