if else condition is not run properlly - php

This is my code and I am unable to run my simple condition. I have used all the ways but it's not working. As I wanted that if count is available then show count and if not then echo 0 in . I know it is simple but I am stuck on it.
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "usman";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query(
"SELECT COUNT(*) as cnt
FROM ams
where empid= {$_SESSION['sess_user_id']}
GROUP BY leavetype
HAVING leavetype = 'Annual'"
);
if (!$result) {
echo "<td>";
echo 0;
echo "</td>";
} else {
foreach ($result as $row) {
echo "<td>" . $row['cnt'] . "</td>";
echo "<br>";
}
}
?>

Your solution
<?php
session_start();
$hostname = "localhost";
$username = "root";
$password = "";
$db = "usman";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query("SELECT COUNT(*) as cnt FROM ams where empid= {$_SESSION['sess_user_id']} GROUP BY leavetype HAVING leavetype = 'Annual'");
if (!$result) {
echo "<td>" . 0 . "</td>";
} else {
foreach($result as $row) {
echo "<td>" . $row['cnt'] . "</td>";
echo "<br>";
}
}
?>
Explanation
It appears you are missing a } at the end of your if-else loop. Additionally, if you are using $_SESSION super-global variables, you need to invoke session_start() first.

Note: While using if else conditions from the Query it is advisable to echo the Query and exit the operations after that line so that we can see the query that we have to execute in the browser and you can navigate to phpmyadmin and place the query in SQL and click on GO. So that this is one of the very easy method to find whether the query runs or not.
Missing Condions:
Session Start is missing in the file
Close brace for the loops opened is missing
General Instruction:
Sometimes if the query is not executing properly also the result of the query will return FALSE so that it is adviced to take the count of the rows after tht query is executed and perform the operations after that.
Your Correct Code look like:
<?php
session_start();
$hostname = "localhost";
$username = "root";
$password = "";
$db = "usman";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query("SELECT COUNT(*) as cnt FROM ams where empid='".$_SESSION['sess_user_id']."' GROUP BY leavetype HAVING leavetype = 'Annual'");
$count = $result->num_rows;
if($count==0)
{
echo "<td>" . 0 . "</td>";
}
else {
foreach($result as $row) {
echo "<td>" . $row['cnt'] . "</td>";
echo "<br>";
}
}
?>
If you check the condition with the count of the query executed you can attain your solution in a better way and you can understand very easy so that it avoids confusion if you look at the code some years back too.

Related

Displaying results of SQL query as a table?

I am trying to output the results of an SQL query as a table on a page on my website. I have found a few solutions online but I can't get any of them to work properly. Right now I copied and pasted a bit of code to just output the first two columns but I can't figure out how to get every column in a table. I am new to PHP and web development in general so any help would be appreciated.
My PHP:
<?php
SESSION_START() ;
$servername = "localhost";
$username = "MY USERNAME";
$password = "MY PASSSWORD";
$dbname = "MY DATABASE NAME";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$_session['userid'] = $userlogged;
$sql = "SELECT * FROM `climbs` WHERE `userlogged` = '" . $_SESSION['userid'] . "'";
$result = mysqli_query($conn,$sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["climb-id"]. "</td><td>" . $row["climbname"]. " " . $row["cragname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
check with var_dump :
some like that:
$result = mysqli_query($conn,$sql);
var_dump($result);
if ($result->num_rows > 0) {
maybe the query it's wrong.

PHP Array ForEach SQL Query

I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.
//Decode JSON file to an Object
$json_d = json_decode(file_get_contents("results.json"));
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table><tr><th>First Name </th><th>Last Name </th><th>Grade </th></tr>";
foreach($userid as $id) {
foreach($grade as $grd) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["firstname"]. "</td><td>" . $row["lastname"]. "</td><td> " . $grd . "</td></tr>";
}
} else {
echo "ERROR!";
}
}
}
echo "</table>";
mysqli_close($conn);
I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G.
FirstName LastName Grade
Student 1 85
Whereas I need the other 2 records that are supposed to appear.

PHP loop through array returned by MySQL function

The code below works fine. However I would like to output the results using a loop. I can do it by going through each key individually or as $post[0] for example but not using a loop to go through all the returned fields. All I get is one value of "Array". It looks like the entire array is inserted into a variable I'm not sure what's going on. I have tried http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays. Any suggestions appreciated and also if anyone could explain what is going on that would be great. Thanks.
$ID = $_POST['ID'];
function query($ID){
$servername = "x.x.x.x";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
$resArr[] = $row;
}
return $resArr;
}
$person = query($ID);
foreach($person as $post) {
echo $post['ID'] . "<br>";
echo $post['NAME'] . "<br>";
echo $post['POSITION'] . "<br>";
echo $post['TELEPHONE_NUMBER'] . "<br>";
echo $post['EMAIL'] . "<br>";
}
?>
Its not totally clear what you are asking but I assume you want to loop through the individual fields of the selected rows. As you built an array containing the query results each result itself being an array mysqli_fetch_array($result) then you can just add an inner loop to process the individual row array like so :-
$persons = query($ID);
foreach($persons as $person) {
foreach ( $person as $fieldname => $value ) {
echo $fieldname . '-' . $value . "<br>";
}
}
Group is reserved word of mysql you can use it in backtics ``
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM `GROUP` WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);

displaying a string twice?

i created a script that connects to my database called mysqlconnecter:
<?php
define("DB_USERNAME", "root");
define("DB_PASSWORD", "pass");
define("DB_DATABASE", "adventure_of_dragons");
define("DB_SERVER", "127.0.0.1");
$db_handle = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$db_found = mysql_select_db(DB_DATABASE, $db_handle);
if ($db_found || true) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL) or die(mysql_error());
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
mysql_close($db_handle);
} else {
echo "Database NOT Found " . $db_handle;
}
?>
And then I created another script that includes mysqlconnecter.php and posts the data inside the database:
<?php
include "mysqlconnecter.php";
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
// two <br>'s, so we get an empty line between users
?>
but the output displays the data inside the database twice:
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
I only want it displaying the text once,
What do I do?
Your logic is slightly the wrong way round.
This is because your loop is finished then you are echoing the data so it will always be the last row.
You need to echo whilst in the loop or create an array then loop the array later.
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
//this will echo for EVERY row the loop iterates.
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
}
For your double output i suspect you have included the file twice. But thats guessing as i don't see all of your code.
If you want to keep the display code outside your mysqlconnecter.php file, you could do this in your loop:
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = array(
'id' => $row['member_id'];
'username' => $row['username'];
'password' => $row['password'];
'rank' => $row['rank'];
}
And then in your script:
include "mysqlconnecter.php";
foreach ($data as $key => $value)
{
echo 'ID = ' . $value['id'] . '<br>';
// etc
}
For your "double print" problem, I would try to put a var_dump($data); right after your while() in mysqlconnecter.php, to see what happens exactly.
If the var_dump display correctly reflects the expected result of your query, the problem is elsewhere, possibly that you include mysqlconnecter.php twice, as Dave suggested. To be sure it's included only once throughout your whole code, simply replace include() with include_once().
Are you sure you don't have any mistake? is that all code you show us?
Because logically your script will print once and will print the last data from your members table
I have try it

SELECT * FROM Table Where ID

I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function

Categories