Data showing up in the frontend above where it's called - php

I have a simple class to work with viewing the people who are blacklisted in my web application. Here is the index.php
require_once "../model/ViewBlacklist.php";
// Handling a navigation to the webpage
try {
$viewBlacklist = new ViewBlacklist("view-blacklists.php", "View Blacklists", $navForUser);
} catch (Exception $ex) {
echo $ex->getMessage();
}
Here is the ViewBlacklist class:
class ViewBlacklist {
function __construct(string $page, string $pageTitle, string $navbar) {
if (empty($_POST) && empty($_GET) && empty(file_get_contents("php://input"))) {
$_SESSION["CSRFTOKEN"] = hash("sha512", random_bytes(64));
$csrfToken = $_SESSION["CSRFTOKEN"];
$pageTitle = $pageTitle;
$navForUser = $navbar;
$usernameBlacklist = "<table id='usernameBlacklistTable'>";
$usernameBlacklist .= "<thead><tr><th>Username</th><th>Time Blocked</th><th>When time will expire</th><th>Remove Blacklist?</th></tr></thead>";
$usernameBlacklist .= "<tbody>";
$usernameBlacklist .= $this->getBlacklistedUsernames();
$usernameBlacklist .= "</tbody>";
$usernameBlacklist .= "</table>";
$ipAddressBlacklist = "<table id='ipAddressBlacklistTable'>";
$ipAddressBlacklist .= "<thead><th>Ip Address</th><th>Time Blocked</th><th>When time will expire</th><th>Remove Blacklist?</th></thead>";
$ipAddressBlacklist .= "<tbody>";
$ipAddressBlacklist .= $this->getBlacklistedIps();
$ipAddressBlacklist .= "</tbody>";
$ipAddressBlacklist .= "</table>";
include_once $page;
exit;
}
}
private function getBlacklistedUsernames() : string {
$blacklistedUsernames = "";
$initDB = new DatabaseConfig();
$db = $initDB->start_db();
$sql = "SELECT username, added, allowed FROM blacklisted_users";
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!empty($data)) {
var_dump($data);
} else {
return "<tr><p class='empty-table-return'>There are no blacklisted usernames</p></tr>";
}
}
private function getBlacklistedIps() : string {
$blacklistedUsernames = "";
$initDB = new DatabaseConfig();
$db = $initDB->start_db();
$sql = "SELECT ip_add, added, allowed FROM blacklisted_ips";
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!empty($data)) {
var_dump($data);
} else {
return "<tr><p class='empty-table-return'>There are no blacklisted IP addresses</p></tr>";
}
}
}
The problem is, where I'm calling $this->getBlacklistedUsernames(); or $this->getBlacklistedIps() the return from that data (which is currently in the else, because nothing lives in my blacklist tables right now) is going above my tables, so the words There are no blacklisted usernames appear above the entire <table> element contained in the variable $usernameBlacklist and the same for the ip addresses. Here is how it is called in the frontend:
<?php include_once "../header.php"; include_once "../nav.php"; ?>
<?php echo $usernameBlacklist; echo $ipAddressBlacklist; ?>
<?php include_once "../footer.php";
What is making my return from my get...() functions appear above the variable they're concatenated into?

So the problem is, it was actually an HTML validation problem. It turns out that you can't have an element be a direct descendent of a <tr> element that isn't a <td> element. So the reason it was a problem was because my <p> element had no <td> parent surrounding it, so the html validation failure forced the <p> up to the top.

Related

PHP To Not Display Grid if $Error Is Hit

I have the below syntax which works as it should, and on the button press event will 1st verify that a begin date and end date has been input into the text boxes, if one of them is blank a message writes on screen notifying the user that it is empty.
The issue with my syntax is that even though the error message displays on screen the syntax continues to iterate and the header row for the table is still displayed (and I assume if the query would return data the table would be populated with data as well). How should this syntax be altered so that if an error is displayed on screen the code stops once the error is displayed on screen?
<?php
if(isset($_POST['submit'])){
$begindateerror = false;
$enddateerror = false;
if (empty($_POST['begindate'])) {
$begindateerror = true;
}
if (empty($_POST['enddate'])) {
$enddateerror = true;
}
if ($begindateerror) {
echo "<strong>Please select a begin date.</strong><br>";
} else { }
if ($enddateerror) {
echo "<strong>Please select a end date.</strong><br>";
} else { }
$option = array();
//Build option array for connection string
$db = JDatabase::getInstance( $option );
$tsql = $db->gettsql(true);
$tsql = "SQL tsql";
$db->settsql($tsql);
$tsql = $db->loadObjectList();
$numofrows = mssql_num_rows($tsql);
?>
<table border="1">
<thead>
<tr>
//Create Header Row for the table
</tr>
</thead>
<tbody>
<?php
foreach( $tsql as $result ) {
print "<tr>";
//write the query results to the table
print "</tr>";
}}?>
You can put all of that latter code after the errors inside the else brackets, and then just have the PHP echo the header:
<?php
if(isset($_POST['submit'])){
$begindateerror = false;
$enddateerror = false;
if (empty($_POST['begindate'])) {
$begindateerror = true;
}
if (empty($_POST['enddate'])) {
$enddateerror = true;
}
if ($begindateerror) {
echo "<strong>Please select a begin date.</strong><br>";
} else if ($enddateerror) {
echo "<strong>Please select a end date.</strong><br>";
} else {
$option = array();
//Build option array for connection string
$db = JDatabase::getInstance( $option );
$tsql = $db->gettsql(true);
$tsql = "SQL tsql";
$db->settsql($tsql);
$tsql = $db->loadObjectList();
$numofrows = mssql_num_rows($tsql);
echo '<table border="1"><thead><tr></tr></thead><tbody>';
foreach( $tsql as $result ) {
print "<tr>";
//write the query results to the table
print "</tr>";
}
}
}
?>

PDO and While function in PHP not working

Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.

Update the query to combat google bot hacking

I have a code in php where i m clikcing on women products or any other link for any other product.On click of which i m going to next page and passing the product name in querystring.
And then in next page i m using my sql query,which will give me the list of products which u clicked on first page.There are lot of queries in my project like this one.This query is quite prone to Google bots hacking with SQL injection.Following is the code
<html>
<head>
</head>
<body>
<ul id="list">
<li><h3>tops</h3></li>
<li><h3>suits</h3></li>
<li><h3>jeans</h3></li>
<li><h3>more</h3></li>
</ul>
</body>
</html
Search.php
<?php
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
session_start();
$lcSearchVal=$_GET['name'];
//echo "hi";
$lcSearcharr=explode("-",$lcSearchVal);
$result=count($lcSearchVal);
//echo $result;
$parts = array();
$parts1=array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = '`PNAME` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
$parts1[] = '`TAGS` LIKE "%'.$lcSearchWord.'%"';
//$parts[] = '`CATEGORY` LIKE "%'.$lcSearchWord.'%"';
}
$stmt = $mysqli->prepare('SELECT * FROM xml where'.'PNAME LIKE ?');
var_dump($stmt);
$parts='%women%';
$stmt->bind_param('s',$parts);
$list=array();
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$list[]=$row;
}
}
$stmt->close();
$mysqli->close();
foreach($list as $array)
{
?>
<div class="image">
<img src="<?php echo $array['IMAGEURL']?>" width="200px" height="200px"/></a>
<?php
}
?>
</div>
</body>
</html>
The query i m using above is quite prone to Google Bot hacking.Please guide me what should i change in this query so that Google Bot wont be able to hack my application with mysql injection..There are some other similar queries in my application to this one.Please guys help me on this.
The reason this is open to SQL injection is that you have not escaped the input.
For example you have the line:-
$parts[] = '`PNAME` LIKE "%'.$lcSearchWord.'%"';
If someone had used a link something like as follows (ignoring the encoding to get it to work in a URL):-
search.php?name=fred%' UNION SELECT * FROM users #
the SQL you would land up with would be something like:-
SELECT * FROM xml WHERE (`PNAME` LIKE "%fred%' UNION SELECT * FROM users #%")limit '.$offset.', '.$limit1.'
then they can execute a query to get data from the other table (possibly one containing the passwords, etc), with just a bit of patience getting the right number of columns, etc.
If you switch to mysqli_* you can use parameterised queries, but these are a minor pain when the SQL itself changes (as yours does in this case with a variable number of LIKE statements).
The simple solution would be to use mysql_real_escape_string() / mysqli_real_escape_string() on the variable you use in the SQL.
foreach( $lcSearcharr as $lcSearchWord )
{
$parts[] = '`PNAME` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
$parts1[] = '`TAGS` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
//$parts[] = '`CATEGORY` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
}
It is worth switching to mysqli_* if you can.
EDIT
Played with script using mysqli_() and a class and function to cope with variable numbers of parameters
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
if (array_key_exists('name', $_GET))
{
$lcSearchVal = $_GET['name'];
$lcSearcharr = explode("-",$lcSearchVal);
$result = count($lcSearchVal);
$parts = array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = "%$lcSearchWord%";
}
$bindParam = new BindParam();
$parms = array();
foreach($parts as $aPart)
{
$parms[] = ' PNAME LIKE ? ';
$bindParam->add('s', $aPart);
}
$query = 'SELECT IMAGEURL FROM xml where '.implode(' OR ', $parms);
$stmt = $mysqli->prepare($query);
if ($stmt)
{
call_user_func_array(array($stmt, "bind_param"), refValues($bindParam->get()));
if ($stmt->execute())
{
while ($row = $stmt->fetch())
{
echo '<div class="image"><img src="'.$row['IMAGEURL'].'" width="200px" height="200px"/></a>';
}
}
else
{
echo $mysqli->error;
}
$stmt->close();
$mysqli->close();
}
else
{
echo $mysqli->error;
}
}
else
{
?>
<ul id="list">
<li><h3>tops</h3></li>
<li><h3>suits</h3></li>
<li><h3>jeans</h3></li>
<li><h3>more</h3></li>
</ul>
<?php
}
?>
</div>
</body>
</html>
<?php
function refValues($arr)
{
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value) $refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
class BindParam
{
private $values = array(), $types = '';
public function add( $type, $value )
{
$this->values[] = $value;
$this->types .= $type;
}
public function get()
{
return array_merge(array($this->types), $this->values);
}
}
?>

How to make echo results in table hyperlinks

I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);

PHP mySQL search script for website

I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !

Categories