Select from MySQL based on HTML form - php

A HTML form contain 4 fields (first name, last name, mobile and attendid). This is a search form to find a record in the attend mysql table. All of these fields are optional with intention being that the more fields you enter in the form, you are narrowing down the search. I know that the issue is with the first SQL as it is not taking into account all the variables.
The second bit to confuse it in more... Where results are echoed in a table, the last field of the echoed table should contain data that is selected from the second SQL statement but this data is in another table.
Sorry if anything is vague but I have no idea how to approach this, been looking at it too long!
Thanks so much for you help!
<html>
<body>
<table>
<table border="1">
<tr><th>AttendeeID</th><th>Wristband</th><th>Firstname</th><th>Lastname</th><th>Telephone
</th><th>Mobile</th><th>Address 1</th><th>Address 2</th><th>Town</th><th>Postcode</th><th>
E-Mail</th><th>Medical Notes</th><th>Last Reader Tap</th></tr>
<?php
include "checkmysqlconnect.php";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mobile = $_POST['mobile'];
$attendid = $_POST['attendid'];
$search = $_POST['search'];
if ($search == "Search") {
if ($firstname == '' AND $lastname == '' AND $attendid == '' AND $mobile == '') {
header("Location: searchattendform.php?result=1");
$error = true;
}
if ($error != true) {
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' OR `lastname` = '".$lastname."' OR `attendid` = '".$attendid."' OR `mobile` = '".$mobile."'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
$sql1 = "SELECT `readerid` FROM `taps` WHERE `attendid` = '".$attendid."' ORDER BY `time` DESC LIMIT 1";
$query1 = mysql_query($sql1);
if ($count > 1) {
echo "More than one matching attendee. Entering more details will help narrow down results.";
while($value = mysql_fetch_assoc($query));
while($value1 = mysql_fetch_assoc($query1)) {
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname'].
"</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1'].
"</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email'].
"</td><td>".$value['medical']."</td><td>".$value1['readerid']."</td></tr>";
} } else {
if ($count == 0) {
header("Location: searchattendform.php?result=2");
} else {
if ($count == 1) {
($value = mysql_fetch_assoc($query));
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname'].
"</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1'].
"</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email'].
"</td><td>".$value['medical']."</td><td>".$value1['readerid']."</td></tr>";
} else {
echo "There was an issue searching attendees. Please contact SOFia Admin.";
} }
}
}
}
?>
</table>
</body>
</html>

Take a look at your outer loop while($value = mysql_fetch_assoc($query));.
Shouldn´t this not be while($value = mysql_fetch_assoc($query)){?

Related

Dropdown to read in and sort users with PHP

I am working on a project where I need to read in users (am using MySQL) and be able to sort 1. Men/Women 2. Salary (eg. 30k+, 50k+, 100k+...)
I've tried setting up a select dropdown but for some reason it's showing only the men, even if I select women.
<form action="#" method="post">
<select name="Gender">
<option value=''>Select Gender</option>
<option value="Men">Men</option>
<option value="Women">Women</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
if(isset($_POST['submit']) && $_POST['submit'] = "Men"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
elseif (isset($_POST['submit']) && $_POST['submit'] = "Women"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
else {
print("-");
}
You've assigned the values in the ifs instead of comparing against them. Also, you've used the wrong input to compare against. $_POST['submit'] will always contain the value Get Selected Values.
if (isset($_POST['submit']) && $_POST['Gender'] === "Men") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} elseif (isset($_POST['submit']) && $_POST['Gender'] === "Women") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} else {
print("-");
}
Here's the code a little more simplified and less redundant. And under the assumption that you're using PHPs PDO.
if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
$gender = $_POST['Gender'] ?? null; // your old $selected_val variable
if (!$gender) {
// do something to abort the execution and display an error message.
// for now, we're killing it.
print '-';
exit;
}
/** #var PDO $dbConnection */
$dbConnection = create_Conn();
$sql = 'SELECT * FROM users WHERE kon = :gender';
$stmt = $dbConnection->prepare($sql);
$stmt->bindParam('gender', $gender);
$stmt->execute();
foreach ($stmt->fetchAll() as $user) {
if (isset($_SESSION['anvnamn'])) {
// Prints user data
} else {
// Prints user data but emails
}
}
}
As Dan has provided a grand answer prior to mine, this is now just a tack on for something to review.
If you look at your form you have two elements.
On Submission, your script will see..
Gender - $_POST['Gender'] will either be '', 'Men', or 'Women'
Submit - $_POST['submit'] will either be null or the value "Get Selected Values".
It can only be null if the php file is called by something else.
You can see this by using the command print_r($_POST) in your code just before your first if(). This allows you to test and check what is actually being posted during debugging.
So to see if the form is posted you could blanket your code with an outer check for the submit and then check the state of Gender.
The following has the corrections to your IF()s and some suggestions to also tidy up the code a little bit.
<?php
// Process the form data using Ternary operators
// Test ? True Condition : False Condition
$form_submitted = isset($_POST['submit'])? $_POST['submit']:FALSE;
$gender = isset($_POST['Gender'])? $_POST['Gender']:FALSE;
if($form_submitted){
if($gender == 'Men') {
// Stuff here
}
else if($gender == 'Women') {
// Stuff here
}
else {
print("-");
}
} else {
// Optional: Case where the form wasn't submitted if other code is present.
}
You could also consider using the switch / case structure. I'll leave that to you to look up.

Running a query with missing variables

This script is selecting data based on optional fields in a HTML form. Although they are optional fields, at least 1 must be entered with the idea being that the more fields entered, the more likely you are to get a single result. For test I have two records with the same first and last name but different ID's and mobile numbers. At the moment when entering a name, 2 fields are given... Correct but when entering a mobile or ID, two results are still displayed.
Ive tried reading into passing missing variables in an SQL query but haven't got very far. Anything blindingly obviously wrong?
Thanks
<?php
include "checkmysqlconnect.php";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mobile = $_POST['mobile'];
$attendid = $_POST['attendid'];
$search = $_POST['search'];
if ($search == "Search") {
if ($firstname == '' AND $lastname == '' AND $attendid == '' AND $mobile == '') {
header("Location: searchattendform.php?result=1");
$error = true;
}
if($error != true) {
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if ($count > 1) {
while($value = mysql_fetch_assoc($query)) {
echo "More than one attendee with this name. Entering more details will help narrow down results.";
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} } else {
if ($count == 0) {
header("Location: searchattendform.php?result=2");
} else {
if ($count == 1) {
($value = mysql_fetch_assoc($query));
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} else {
echo "The was an issue searching attendees. Please contact SOFia Admin.";
} }
}
}
}
?>
One issue you have is that your query always checks all the variables:
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
You probably want to break it up, and build it dynamically, something like this:
$sql = "SELECT * FROM `attend` WHERE ";
$whereArray = [];
if ($lastName){
$whereArray[] = "`lastname` = '".$lastname."'";
}
if ($firstname){
$whereArray[] = "`firstname` = '".$firstname."'";
}
//etc...
$sql .= join(" AND ", $whereArrray);
You will need to modify this to use parametrization, but this should see you in the right direction:
include "checkmysqlconnect.php";
((isset($_POST['firstname']) && $_POST['firstname'] != '') ? $firstname = '%'.$_POST['firstname'].'%' : null); //prevents unneeded variables
...
if (!(isset($firstname) or isset($lastname) or isset($attendid) or isset($mobile))) { //checks that at least one variable has been provided
...
$sql = "SELECT * FROM `attend` WHERE 1=1"; //returns all; necessary for building the query since you have an unknown number of parameters
(isset($firstname) ? $sql .= " AND `firstname` like '".$firstname."': null); //adds to the query only if the variable exists
...
?>
I highly recommend using some kind of database wrapper class. This will help generate the SQL for you. There are many other reasons why this is a good idea.
There are plenty of MySQL wrappers and most frameworks have one. You could try for example, CodeIgniter, which is very simple framework to install and work with. Then, to create the query you would do something like:
<?php
if(isset($_POST['firstname']) && !empty($_POST['firstname'])) {
$this->db->where('firstname', $_POST['firstname']);
}
if(isset($_POST['lastname']) && !empty($_POST['lastname'])) {
$this->db->where('lastname', $_POST['lastname']);
}
...
$results = $this->db->>get('attend');
foreach($results->result() as $row)
{
echo $row->firstname;
}
?>
Try to place var_dump($sql); die(); after the $sql statement and test what that returns.

Passing php variables through pages / sql

i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']

PHP/MySQL - Validating Usernames with Exceptions for Additional Characters

I've created an athletic league website with dynamic schedules and standings using PHP and MySQL. One of the basic functions of the website is for schools to select a game on the schedule that's already been played and log-in to report the score. You can see an example of the score reporting page below:
http://www.parochialathleticleague.org/report_score.html?league=test_league&game_id=5&away_team=St.%20Polycarp&home_team=St.%20Columban
After several months of work, everything seems to be working just right. However, I realized one important oversight this morning, just before the schedules for the new season are about to go live:
Some of our schools have multiple teams in each division because they have extra students. So, for example, there may be a St. Barbara AND a St. Barbara #2 participating in the same league and/or division. Sometimes, there are as many as three of four teams from the larger schools.
This is a problem because the validation code that I've written checks the school usernames to make sure they match the master school user accounts in the MySQL database before being allowed to report a score. Therefore, St. Barbara would not be authorized to report a score for their St. Barbara #2 team, even though they belong to the same school! I don't want to create separate user accounts for every team belonging to that school, so I need to modify the code in some way. I would like St. Barbara to be able to log-in with the same username for all of their different teams, regardless of whether or not there are additional characters at the end (if that makes sense).
Here's the function from my script that validates the username (school) to make sure they're one of the two teams participating in the game in question:
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
Next, here's the function that later validates that the username and password match one of the records in the database:
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// ***a whole bunch of other stuff that I'm omitting because it's not relevant
}
}
Is there anyway to add an "addendum", so to speak, to the code that would make an exception for schools that have multiple teams? Sort of like:
elseif ($_POST['school'] == $_POST['away_team'] **MINUS ADDITIONAL INTEGERS AT THE END** || $_POST['school'] == $_POST['home_team'] **MINUS ADDITIONAL INTEGERS AT THE END**) {
$validate = 'true';
}
Sorry for the whole long spiel. Just wanted to make sure I explained it properly! Any thoughts? Your feedback is much appreciated.
EDIT - Here's the entire script for those that were interested:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the away score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_confirm = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
// Validate the home score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the home score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['$home_score']) && $_POST['$home_score'] < 0 ) {
echo "You entered an invalid score for the home team.<br>";
$validate = 'false';
} else {
$home_score_confirm = mysqli_real_escape_string($db, trim($_POST['home_score']));
$validate = 'true';
}
// Determine the winner and loser, and set variables:
if ($_POST['away_score'] > $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['away_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['home_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$tie = 'no';
} else if ($_POST['away_score'] < $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['home_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['away_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$tie = 'no';
} else if ($_POST['away_score'] == $_POST['home_score']) {
$tie = 'yes';
$tie1 = mysqli_real_escape_string($db, trim($_POST['away_team']));
$tie2 = mysqli_real_escape_string($db, trim($_POST['home_team']));
$tie_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
}
// Declare remaining hidden inputs as variables:
$league = mysqli_real_escape_string($db, $_POST['league']);
$game_id = mysqli_real_escape_string($db, $_POST['game_id']);
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// Get the game ID:
$q2 = "SELECT $game_id FROM $league";
$r2 = mysqli_query($db, $q2);
// Get the row for the game ID:
$row = mysqli_fetch_array($r2, MYSQLI_NUM);
// Perform an UPDATE query to modify the game scores:
$q3 = "UPDATE $league SET home_score='$home_score_confirm', away_score='$away_score_confirm' WHERE game_id=$row[0]";
$r3 = mysqli_query($db, $q3);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the winning team in the standings:
$q4 = "SELECT school_id FROM test_league_standings WHERE school_name='$winner'";
$r4 = mysqli_query($db, $q4);
// Get the row for the school:
$row2 = mysqli_fetch_array($r4, MYSQLI_NUM);
$q5 = "UPDATE test_league_standings SET games=games + 1, win=win + 1, pts_for=pts_for + '$winner_score', pts_against=pts_against + '$loser_score' WHERE school_id=$row2[0]";
$r5 = mysqli_query($db, $q5);
$q6 = "UPDATE test_league_standings SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row2[0]";
$r6 = mysqli_query($db, $q6);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the losing team in the standings:
$q7 = "SELECT school_id FROM test_league_standings WHERE school_name='$loser'";
$r7 = mysqli_query($db, $q7);
// Get the row for the school:
$row3 = mysqli_fetch_array($r7, MYSQLI_NUM);
$q8 = "UPDATE test_league_standings SET games=games + 1, loss=loss+1, pts_for=pts_for + '$loser_score', pts_against=pts_against + '$winner_score' WHERE school_id=$row3[0]";
$r8 = mysqli_query($db, $q8);
$q9 = "UPDATE test_league_standings SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row3[0]";
$r9 = mysqli_query($db, $q9);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
if ($confirm != 'false') {
header("Location: schedules_test.html?league=" . $league);
} else {
echo "The scores could not be reported due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
} else {
echo "Your school and password combination do not match those on file for this game.";
}
}
mysqli_close($db);
?>
For the moment I'm going to assume that you're validating that $_POST['away_team'] and $_POST['home_team'] are valid and correct.
If you just want to check that $_POST['away_team'] begins with the string $_POST['school'], you can use the strpos function:
elseif (strpos($_POST['away_team'], $_POST['school']) === 0 || strpos($_POST['home_team'], $_POST['school'])) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
}
I'd like to assent to tadman's comment about SQL injection. Even if you aren't willing to rewrite your application to take advantage of the superior methods of injecting data into queries, you absolutely should escape your data when you run your query. Do not escape it anywhere else. If you do, eventually you will forget to escape it and it won't be as obvious as it should be. For example:
if ($validate != 'false') {
$q1 = sprintf(
"SELECT school_id FROM user_schools WHERE (school_name='%s' AND pass='%s')",
mysqli_real_escape_string($_POST['school']),
mysqli_real_escape_string($_POST['pass'])
);
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// ***a whole bunch of other stuff that I'm omitting because it's not relevant
}
}

php mysql if row is empty and if isn't empty

Code:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table`
WHERE `Username` = '$Username'
ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) { ?>
<?php if(!isset($db['article'] && $db['subject'])) {
echo "Your articles";
} else {
echo "You have no articles added!";
} ?>
<?php } ?>
So I want the rows for example(db['article'] and $db['subject']) from a specific username (see: $Username = $_SESSION['VALID_USER_ID'];) to echo the information if is not empty else if is empty to echo for example "You have no articles added!"
If is some information in the rows the code works, echo the information BUT if the rows is empty don't echo nothing, the code should echo "You have no articles added!" but this line don't appear, where is the mistake?
I tried for if !isset, !empty, !is_null but don't work.
I think what you're trying to achieve is:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
if(mysql_num_rows($q) > 0)
{
echo "Your articles:\n";
while($db = mysql_fetch_array($q)) {
echo $db['subject']." ".$db['article']."\n";
}
}
else
{
echo "You have no articles added!";
}
?>
I don't understand. Do you have article rows with username, but without article, i.e.:
| id | user | article |
-------------------------------------
| 1 | X | NULL |
If so, you can test with:
if($db['article'] == NULL) { .... } else { .... }
Otherwise, if you don't have a row with user=x, when there are no record, mysql will return an empty result.
So, basicly, if no rows are found on selection: SELECT * FROM article_table WHERE Username = 'X';, you can test
if(mysql_num_rows($q) > 0) { .... } else { .... }
However, mysql_ functions are not recommended anymore. Look at prepared statements.
You have a logic error in your if statement -- what you want is to check if both the article and subject are set.
With your current code, you compare $db['article'] with $db['subject'], and check if the result is set. You need to change it a bit :
Instead of :
if(!isset($db['article'] && $db['subject'])) {
Try:
if(isset($db['article']) && isset($db['subject'])) ...
I would do something like this:
$articles='';
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
if(isset($db['article']) && isset($db['subject'])) {
$articles .= $db['article']."<br/>";
}
}
if($articles != ''){
echo $articles;
}
else{
echo "No articles";
}
?>
fastest way to achieve what you want is by adding a variable that will verify if the query returned any rows:
<?php $Username = $_SESSION['VALID_USER_ID'];
$i = 0;
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
$i = 1;
if(!isset($db['article'] && $db['subject'])) { echo "Your articles"; } ?>
<?php }
if ($i == 0) echo "You have no articles";
?>
You tried to echo "no articles" in the while loop, you get there only if the query returns information, that is why if it returns 1 or more rows, $i will become 1 else it will remain 0.
In your case:
$numArticles = mysql_num_rows($q);
if($numArticles > 0)
echo 'Your articles';
else
echo 'No articles :((((';
I recommend tough moving on to PDO to communicate with DB.

Categories