Code is not displaying database information from query - php

I am trying to build a staff page, which quesries the MySQLi database holding registered users, and displays only moderators, admins, and super admins. This is the code I have. For some reason, nothing shows up in the table on the page. I have no fatal erros, so the code is "technically" correct, however the logic isn't outputting what I want.
The code below should query the database, fetch the row of info as an array, output the username and registration date into the table, and keep looping until there are now more rows left. Though, as I said, nothing is output. I have no idea what I am doing wrong.
If it makes a difference, this is a custom page in myBB forum software. I know the page is setup correctly because everything displays, except the info I am attempting to pull form the database.
<?php
global $headerinclude, $header, $theme, $footer, $lang;
if(!$mybb->user['uid'])
{
error_no_permission();
}
$lang->load('modcp');
$mysqli = new mysqli("XXXXXXXXX","XXXXXXXXXXX","XXXXXXXXX","XXXXXXXX");
$query_result = $mysqli->query("SELECT uid,username,usergroup,regdate FROM mybb_users ORDER BY regdate ASC");
if ($db->num_rows($query_result) > 0)
{
$usertablerows = "";
while($users = mysqli_fetch_row($query_result))
{
if($users['usergroup'] != 3 || $users['usergroup'] != 4 || $users['usergroup'] != 6)
{
$pass = "true";
}
else
{
$staffuseruid = $users['uid'];
$rawregdate = $users['regdate'];
$usergroupvalue = $users['usergroup'];
$staffusername = $users['username'];
$staffuser = get_user($staffuserid);
$usertablerows .= ' <tr>
<td class="trow1">' . build_profile_link($staffusername, $staffuserid). '</tf>
<td class="trow2">' . my_date($mybb->settings['dateformat'], $rawregdate). '</td>
</tr>';
}
}
}
$template='<html>
<head>
<title>'.$pages['name'].'</title>
{$headerinclude}
</head>
<body>
{$header}
<table border="0" cellspacing="1" cellpadding="2" class="tborder">
<tr><td class="thead" colspan="4"><strong>The Staff</strong></td></tr>
<tr>
<td class="tcat"><span class="smalltext"><strong>Username</strong></span></td>
<td class="tcat"><span class="smalltext"><strong>Registered</strong></span></td>
</tr>
{$usertablerows}
</table>
{$footer}
</body>
</html>';
mysqli_close($mysqli);
$template=str_replace("\'", "'", addslashes($template));
add_breadcrumb($pages['name']);
eval("\$page=\"".$template."\";");
output_page($page);
?>

You can check by appending database name to table name in mysql query.

Related

Bootstrap modal shows the same result even after SQL query is changed

I have a bootstrap modal that will dynamically retrieve sql data based on sql query. What should happen is that an sql query will be executed and the matching records shall be displayed, and if a selected record doesn't match the sql query, then the modal shall be empty.
first record selection
Now, this is the .php code:
<?php
if(isset($_POST["student_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "root", "tnstudentregistrationdb");
//This is where the problem is, but I just couldn't really figure out what's wrong. Basically, if I select a record from my modal and its studentID is 1 but doesn't have noteTitle record of 'SECOND NOTE', no data should be displayed, however in this case the record with noteTitle 'SECOND NOTE' still shows up.
$query = "SELECT * FROM studentNotes WHERE studentID = '".$_POST["student_id"]."' AND noteTitle = 'SECOND NOTE'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td width="30%"><label>Student ID</label></td>
<td width="70%">'.$row["studentID"].'</td>
</tr>
<tr>
<td width="30%"><label>Note Title</label></td>
<td width="70%">'.$row["noteTitle"].'</td>
</tr>
<!--Make note title unique in sql database-->
<tr>
<td width="30%"><label>Note</label></td>
<td width="70%">'.$row["notes"].'</td>
</tr>
';
}
$output .= "</table></div>";
echo $output;
}
?>
This is what happens if I select a record with Student ID 2:
The modal should be empty since in my database, the query 'SELECT * FROM studentNotes WHERE studentID = 2 AND noteTitle = 'SECOND NOTE';' returns an empty set
sql query in mysql shell
I have already tested the bootstrap modal and the html table element that I used in this system, and in conclusion, the problem really is from the above .php code I just really couldn't figure out what's wrong since I have also of course have already manually tried to run sql queries on sql shell directly and data retrieval there is completely just fine, please help and give beneficial feedbacks, thank you so much.

How to pass query results from the results page to a different php page

I know how to get search results from one page to another, but the scenario I'm in right now is that I have a search form (searchform.php) where the user enters search criteria into a field or fields, clicks the submit button and the results display in a table on the search.php page. Now what I need to do is send those query results to another page (list.php) which is a page formatted as a report. I've tried using $_SESSION, $_GET, foreach, etc. And I've also tried comparing my code with the code on the other pages on my site and on the internet, but to no avail. None seems to fit my situation. Right now I'm using $_SESSION and only getting the word "Array" in each column of the table and getting only one row of data. When I did get actual data from the query it only brought over the last result from the query. For example, the search.php showed 6 results, but the list.php page only showed the last result. I've spent days on this. Will someone please try to help me?
Here is part of the code on my search.php page (it works - although I'm not sure I need the $_SESSION info in the middle):
if !empty($_POST['id'])||!empty($_POST['title'])||!empty($_POST['numavail'])||!empty($_POST['categoryname'])||!empty($_POST['genretype'])){
$id = mysqli_real_escape_string($dbc, $_POST['id']);
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
$query="SELECT * FROM dvd WHERE (title LIKE '%$title%')
AND (numavail LIKE '%$numavail%')
AND (categoryname LIKE '%$categoryname%')
AND (genretype LIKE '%$genretype%')
ORDER BY title ASC";
}else {
$query="SELECT * FROM dvd ORDER BY title ASC";
}
$result = #mysqli_query ($dbc, $query);
$num = mysqli_num_rows($result);
if ($num > 0) { // If it ran OK, display all the records.
echo "<h4>Your search returned $num records.</h4><p></p>";
//Table header:
echo '<table align="center" width="950px" cellspacing="0" border=".5px" ! important><tr>
<th>Title</th><th>Qty</th><th>Category</th><th>Genre</th></tr>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
//Fetch all the records...
session_start();
$_SESSION['id']=['id'];
$_SESSION['title']=['title'];
$_SESSION['numavail']=['numavail'];
$_SESSION['categoryname']=['categoryname'];
$_SESSION['genretype']=['genretype'];
echo '<td align="left" width="20%" height="25px">'.$row['title'].'</td>
<td align="right" width="5%">'.$row['numavail'].'</td>
<td align="left" width="20%">'.$row['categoryname'].'</a></td>
<td align="left" width="30%">'.$row['genretype'].'</a></td>
<td align="center" width="5%"><a href=../dvd/updateform.php?id='.$row['id'].'><em>Update</em></a></td>
<td align="center" width="5%"><a href=../dvd/deleteconfirm.php?id='.$row['id'].'><em>Delete</em></a></td>
</tr>
';
}
// End of While statement
echo "</table>";
Here is part of the code on my list.php page (not working):
session_start();
include ('../../includes/reportheader.php'); // Include the header file.
echo ('<h1>DVD SEARCH RESULTS</h1>');
//Table displaying records.
'<div id="rpttable">';
echo '<table align="center" width="750px" cellspacing="0" border=".5px" ! important><tr>
<th>Movie Title</th><th>Qty</th><th>Category</th><th>Genre</th></tr>';
echo '<td align="left" width="20%" height="25px">'.$_SESSION['title'].'</td>
<td align="center" width="5%">'.$_SESSION['numavail'].'</td>
<td align="left" width="20%">'.$_SESSION['categoryname'].'</td>
<td align="left" width="30%">'.$_SESSION['genretype'].'</a></td>
</tr>
</div>
';
echo "</table>";
Move session_start(); at the first line of your document or else session will fail unless output buffering setting is on.
In your while loop, name your session variable properly so it won't mess with other session variables in the future. Also set the values of your session elements with that from $row variable.
From: $_SESSION['id']=['id']; - to - $_SESSION['search_result']['id'][]=$row['id']; - so on.
Also before your while loop you have to delete your previous search results before adding new ones by adding line unset($_SESSION['search_result']);. Else old and new results will be displayed together.
In listing.php you have to loop through $_SESSION['search_result'] to display the passed search results. Something like:
for($i=0; $i<count($_SESSION['search_result']['id']); $i++ ){
echo '<tr><td align="left" width="20%" height="25px">'.$_SESSION['search_result']['title'][$i].'</td>
<td align="center" width="5%">'.$_SESSION['search_result']['numavail'][$i].'</td>
<td align="left" width="20%">'.$_SESSION['search_result']['categoryname'][$i].'</td>
<td align="left" width="30%">'.$_SESSION['search_result']['genretype'][$i].'</a></td>
</tr>';
}
You can use GET, POST method or Session, Cookie for passing data from one page to another page
Example
GET and POST
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
PHP code
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Change the method for the form to post if you want to do it via post.
Both are equally insecure, although GET is easier to hack.
GET method can handle less amount of data.
For handling higher amount of data, use POST Methode and also check the "post_max_size" in php.ini file.
Session
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
Cookie
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies is that the sessions value stored on the server and cookies stored in client browser memory.

a redirection to the profile

Ive got a code running smoothly which shows the list of people who are level 8 as shown below
I want when a person click on the username of the people it redirects them to their profile, actually i've got no clue or ideas of how could that be done. So i need a little bit of help to get some points on this.
Here is the code to show the above output
<?php
$lvl8 = 0;
$content = "";
$query = $koneksi->prepare("SELECT `user`, `level`, `LastOnlineDate` FROM `playerdata` WHERE `banned`=0 AND `level`=8");
$query->execute();
while($data = $query->fetch())
{
$lvl8++;
$content .= "<tr><td>".$lvl8."</td>";
$content .= "<td>".$data['user']."</td>";
$content .= "<td>".$data['LastOnlineDate']."</td></tr>";
}
?>
<table class="table table-bordered">
<thead>
<tr>
<td colspan='6'><h4><small>Level 8 - Trusted Admin (Total <?php echo $lvl8 ?>)</small></h4></td>
</tr>
<td><h5>Number</h5></td>
<td><h5>Username</h5></td>
<td><h5>Last Login</h5></td>
</thead>
<?php
if($query->rowCount() == 0)
{
echo "<tr><td colspan='6'><small>No rows found</small></td></tr>";
}
echo $content;
?>
</table>
first thing you should do is, have an a tag for name, like this
$content .= "<td><a href='link to a new file?id=userid from database'>".$data['user']."</a></td>";
In the new page, you can capture the id of the user, run a query to fetch the details of obtained id and then show the details obtained from database.
Create a http query or post form for your action.
like this in your foreach loop.
GET
<?php echo $username ?>
in your ending script for example a controller in an mvc architecture:
$id = $_GET['user_id'];
// do database stuff and view
Do your query using $id and fetch the result then display your view.
Basically you iterate over user id's to create links that carry the id of the clicked user in order to fetch the selected id.

PHP + MySQL + Cookies, why is this not loading properly?

I've got a PHP page with 2 MySQL statements in various parts of the code. I'm using the generated result sets to set cookie values then call it later. Yet, when I call the cookie data, it does not update the display of the cookie values until after a 2nd refresh. To Better understand, Here's the 3 sections of code:
<?php
include 'functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$SqlStatement = "SELECT Deceased.PK_Deceased, Deceased.Date_Death, Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info WHERE Deceased.FK_Personal_Info = '".$_POST['cboDeceased']."'";
$result = ExecuteSql($SqlStatement);
if(mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array($result);
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
setcookie('deceasedName', ($row['First_Name']." ".$row['Last_Name']), time()+360000, '/');
setcookie('deceasedDoD', $row['Date_Death'], time()+360000, '/');
}
}
?>
This is the code that pulls the data from the postback. I think that this is the part that is incorrect, but I'm not sure.
<tr>
<td width="25%" rowspan="2" align="center">Current User: <?php echo $_COOKIE['username']; ?> </td>
<td width="25%" rowspan="2" align="center">Current Deceased: <?php if(isset($_COOKIE['deceasedName']))echo $_COOKIE['deceasedName']; ?></td>
<td width="50%" rowspan="2" align="center">Deceased Date of Death: <?php if(isset($_COOKIE['deceasedDoD']))echo $_COOKIE['deceasedDoD']; ?></td>
This is the code to load the cookie data into fields and the part that takes the 2nd refresh to display properly.
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table align="center" width="500" border="0.5">
<tr>
<td width="176" align="right" style="font-weight:bold;">Please select deceased:</td>
<td width="214">
<select name="cboDeceased" id="cboDeceased">
<option>Select...</option>
<?php
$SqlStatement = "SELECT Deceased.PK_Deceased , Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info";
$res = ExecuteSQL($SqlStatement);
while($row = mysqli_fetch_array($res))
{
echo "<option value='".$row['PK_Deceased']."'>".$row['First_Name']." ".$row['Last_Name']."</option>";
}
?>
This is the code that passes a variable based on ID to the 1st code block. This part works fine.
function ExecuteSQL($SQL)
{
$con = mysqli_connect("localhost", "root", "", "exec_support_db");
$res = mysqli_query($con, $SQL);
mysqli_close($con);
return $res;
}
Here's the code for the ExecuteSQL function. I know that this isn't the problem.
I think the problem is up above in the 1st code block, but I'm not sure. I've tried everything I can and am now out of ideas. Any help would be appreciated.
Beyond the SQL injection mentioned above by DaveRandom take a look at the php manual on how setcookie works:
http://php.net/manual/en/function.setcookie.php
It mentions specifically the info is injected into the headers, and therefor not available until your next page load. You probably want to do something like
if(isset($_COOKIE['deceasedID']))
{
$deceasedID = $_COOKIE['deceasedID'];
}
else
{
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
$deceasedId = $row['PK_Deceased'];
}

Hyperlinks from rows in Mysql Table

The thing is that I have made application form which saves in db. And I want on other page to display just some rows of the mysql table in php table where the first column is hyperlink to the single application as it is in the form. My question is how it can automatically make hyperlinks and pages for each form?
This is my code for now
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
$data = mysql_query("SELECT * FROM applications ") or die(mysql_error());
echo ' <table width="760" border=1>
<tr>
<th>Заявление<br>От дата:</th>
<th>От/До</th>
<th>Статус</th>
</tr>';
while($info = mysql_fetch_array( $data ))
{
echo '
<tr>
<td>'.$info['today'] .'</td>
<td>От '.$info['data1data'] .'.'.$info['data1mesec'] .'.'.$info['data1god'] .' до '.$info['data2data'] .'.'.$info['data2mesec'] .'.'.$info['data2god'] .' </td>
<td>';
if($info['status'] == 1) {
echo '<img src="Images/approved.jpg" />';
}
else {
echo '<img src="Images/declined.jpg" />';
}
echo ' </td>
</tr> ';
}
echo '</table>';
The result I am trying to get is a table with 3 columns and rows for every application and from the first column of the application I get redirected to a single webpage for that application form and this link to be auto made by code something like "applications.php?id=[application id]"
I don't understand so much but:
<?php
$query = mysql_query("SELECT * FROM applications");
while($t = mysql_fetch_array($query)){
echo ''.$t['name'].'<br/>';
}
?>
Don't know what's the problem.

Categories