How to fetch and dispaly specific data with PDO - php

I'm having issues making my project for lesson attendance and management work the way I'd like it to. Sorry if this has already been addressed here. After days of searching, I still cannot for the life of me find a way to display a limited result set from my DB query to my home page.
This part of the project gets all Towns listed on my homepage like so:
Verona
Mantova
Rovereto
Bardolino
...
What I'd rather want is to get control over whatever is displayed! Specifically, I'd like to have ONLY Rovereto and Bardolino returned (as example). I'm thinking of probably doing this with additional page e.g. index1.php so when this page is loaded it will show only desired values and not all fetched values!
The search function result is also case sensitive. If I type "Bardolino", I get result but with "bardolino", no joy at all. I'm new to this, please help me out. Thank you very much.
File index.php:
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Lesson Number</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<?php
for($i=0; $i < count(User::get_all_users()); $i++){
echo "<tr>";
echo "<td>".User::get_all_users()[$i]['id']."</td>";
echo "<td>".Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['number']."</td>";
echo "<td>".show_town(Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
?>
File user_controller.php:
if(isset($_GET['type']) && $_GET['type'] == 'search'){
global $user_search_list;
$user_search_list= array();
for($i=0; $i < count(User::get_all_users()); $i++){
$user = User::get_all_users()[$i];
$lesson_number = Lesson::get_lesson_by_id($user['lesson_id'])['number'];
$town_name = show_town(Lesson::get_lesson_by_id($user['lesson_id'])['town_id']);
if(strpos($lesson_number,$_GET['search_term']) !== False ||
strpos($town_name,$_GET['search_term']) !== False)
{
$user_search_list[] = $user;
}
}
$_SESSION['search_list'] = $user_search_list;
header("Location: search_user_list.php");
exit();
}
if(isset($_GET['type']) && $_GET['type'] == 'reserve'){
$user = User::get_user_by_id($_GET['user_id']);
if(!empty($_GET['seat_id'])) {
if(count($_GET['seat_id']) * $user['price'] > intval(Balance::get_user_balance($_SESSION['user_id'])['amount'])){
header("Location: reserve.php?user_id=".$user['id']."&balance_error=set");
exit();
}else{
foreach($_GET['seat_id'] as $seat_id){
echo $seat_id;
echo "<br>";
Reservation::create_reservation('', $_SESSION['user_id'], $_GET['user_id'], $seat_id, getdate()[0]);
Balance::update_balance($_SESSION['user_id'], intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) - intval(User::get_user_by_id($_GET['user_id'])['price']));
Seat::reserve_seat($seat_id,$_SESSION['user_id']);
Action::create_action('', "User - ".$_SESSION['user_id'].'reserve Seat ID - '.$seat_id. " on User ID - ".$_GET['user_id'],"reserve" , getdate()[0]);
}
if(count(Reservation::get_all_reservations_by_user($_SESSION['user_id'])) == 5){
Balance::update_balance($_SESSION['user_id'] ,intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) + 10);
header('Location: index.php?reserve_success=set&reward=set');
exit();
}
header('Location: index.php?reserve_success=set');
exit();
}
}
else{
header("Location: reserve.php?user_id=".$user['id']."&seat_error=set");
exit();
}
}
function show_town($id){
return Place::get_place_by_id(Town::get_town_by_id($id)['place_id'])['name'].
}
File User.php:
class User
{
static $id;
static $lesson_id;
static $starting_date;
static $starting_time;
static $arrival_time;
static $price;
static function create_user($id, $lesson_id, $starting_date, $starting_time, $arrival_time, $price){
global $db;
$sql = "INSERT INTO `lesson_database`.`users` (`id`, `lesson_id`, `starting_date`, `starting_time`, `arrival_time`, `price`) VALUES (NULL, '".$lesson_id."', '".$starting_date."', '".$starting_time."', '".$arrival_time."', '".$price."');";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
static function get_all_users(){
global $db;
$sql = "SELECT * FROM `users`";
$db_result = $db->query($sql);
if($db_result){
return $db_result->fetchAll();
}
else {
return False;
}
}
static function get_user_by_id($id){
global $db;
$sql = "SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1";
if(!isset($sql)){
echo "not set";
}
$db_result = $db->query($sql);
if($db_result){
$db_row = $db_result->fetch(PDO::FETCH_ASSOC);
if($db_row){
return $db_row;
}
else {
return False;
}
}
return False;
}
static function delete_user($id){
global $db;
$sql = "DELETE FROM `lesson_database`.`users` WHERE `users`.`id` = '".$id."'";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
}

I feel a little bit like you've jumped ahead and skipped some basics as lots of this doesn't make sense.
Firstly, you've said about using PDO in the title but you're not using PDO in your queries, you really need to be using PDO so if you're not sure how then try and find a good tutorial about using prepared statements.
Secondly, you're doing loads of extra calls within loops and duplicating calls all over the place so I think you could do with looking for a tutorial on design patters and think about how you could streamline this code.
As a very basic you could get all your users once by using a fetchAll (or fetch_assoc i think in mysqli) and then just loop through that variable e.g.
<?php
$users = User::get_all_users;
foreach($users as $user){
$lesson = Lesson::get_lesson_by_id($user['lesson_id']);
echo "<tr>";
echo "<td>".$user['id']."</td>";
echo "<td>".$lesson['number']."</td>";
echo "<td>".show_town(lesson['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
as for your search the simplest way would be to pass a search string in the url and use global $_GET['searchString'] (obviously you will need to sanitize the string) and then search for results directly in sql such as
SELECT * FROM table WHERE town LIKE . $yourvariable .% (ideally in your newly learned PDO style)
then it will be both not case sensitive and will also mean you've got the data in the first place so you don't waste time looping through a bunch of extra rows.
If you need to make this case insensitive in the meantime then the simplest way is to convert the search and the comparison string to the same case (strtolower for example) and then they will match
It also strikes me that your database might not be in good shape as I would be surprised to find that a user table contains lesson ids, so you might want to look into the idea of database normalisation, this will then allow you to do some more creative queries and more easily gather together accurate information for whatever your task is (i.e. make it scalable and manageable).
I hope some of that is helpful, sorry it's not a quick answer but it's not a quick problem I think. Don't fear though, we all started somewhere!!

Related

Implement If condition in PHP array

I am new to PHP function. I think following problem can be solved using function. Here I am able to store html form data in database which is passed from ajax using following code. But I am little bit confused where to implement if condition. If Data has been submitted, I want to stop data replication.
My working php code
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
Now, I want to include above code in following else condition.
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
// insert...
}
}
When I try to merge code, I can't handle. Please help me
You have pretty much everything, you just need to wrap it in a function like this:
function insert() {
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
}
And then you call it like this:
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
insert();
}
}

PHP function returns wrong values

I have this function
function getNick($uid)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
Basically it should return me nick based on user's id. Problem is that I only keep getting '(none)'. What is interesting I printed actual $sqli and copied it into phpMyAdmin and it worked as expected. I even tried to just print nick without IFs but I ended up with empty string. What might be the issue? Am I overlooking something? Thanks
<?php
$con = mysqli_connect("localhost","root","","test");
function getNick($uid,$con)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
echo getNick(1,$con);
?>
it works
variable scope problem
use above method to pass connection in method or
use $GLOBALS['con'] to access connection in method getNick

PHP custom function return value from mysql database

i have looked at the other results for what i'm trying to do, none of them do what i need them to. What i am trying to do is something like this:
myfunction(){
require('./connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='$user'"); //user is defined outside the function but it works in my login function which i use the same way.
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = row['value'];
mysql_close();
return $value;
} else {
$errmsg = "connection failed.";
$value = 0;
return $value;
}
}
In my php file i would do something like this at the top.
$value = myfunction();
This does not work.
Ultimately what i'm trying to accomplish is getting a value from the database and output it from the function in another file.
(this is my first post on stackoverflow so if i need to change this feel free to tell me and i shall)
Your code has several syntax error. Check this, and read my comments:
function myfunction() {
//connect to database
require('./connect.php');
//user is defined outside the function but it works in my login function which i use the same way.
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($user) . "'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
return $row['value']; //Missing $ sign
//No need to create $value if you just return with that.
//mysql_close();
//return $value;
} else {
//Where do you use this errmsg????
$errmsg = "connection failed.";
return 0;
// These 2 lines are unnecessary.
//$value = 0;
//return $value;
}
} //Missing function close
In my example, I've just leave the mysql functions, but please do not use them, they are deprecated. Use mysqli or PDO instead. Also, avoid sql injections by escapeing your variables!
$row = mysql_fetch_assoc($query);
$value = row['value']; // <-------- you forgot the $
and most probably, the correct way to extract the result is,
$row[0]['value'];
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
i'm thinking you forgot a dot here.
require('./connect.php');
And a bit of function improvement
myfunction(){
require_once('../connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='".$user."'"); //user is defined outside the function but it works in my login function which i use the
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = $row['value'];
mysql_close();
}
else{
$errmsg = "connection failed.";
$value = 0;
}
return $value;
}

PHP Code Problem

function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$msg = "true";
}
else
{
$msg = "false";
}
return $msg ;
}
The return value is Object id #1true???? what is object id#1?
Change from:
echo $objUser.check_login($array_login);
to:
echo $objUser->check_login($array_login);
The . operator in PHP does string concatenation, while the arrow allows you to access object methods and attributes.
You're returning the strings "true" or "false" when you probably mean the boolean values true and false.
Oh, and your code is wide open to a visit from Little Bobby Tables. You really should use mysqli and proper prepared statements instead.
Try this:
function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
return true;
}
else
{
return false;
}
}
Let us know what result you get when using that code.
user single quotes and things will start to work better. also check your query for sql injection bug as it does have it.
Change
echo $objUser.check_login($array_login);
to
echo $objUser;
echo check_login($array_login);
You should end up with the following result:
Object id #1
true
My guess is that $objUser was set earlier with something along these lines:
$objUser = new User;
As a result, it is an object (the first one declared) and will return Object id #1 when you just echo it. You will need to read up on classes to understand that more.

editing mysql table with html form

My aim is to have a simple, form based CMS so the client can log in and edit the MySQL table data via an html form. The login is working, but the edit page isn't returning the values from the MySQL table, nor am I getting any errors.
I'm still amateur, and I first started the following code for a class project, but now plan to implement it for a live site. From what I understand I shouldn't have to declare the next/previous/etc. variables at the top, which I tried unsuccessfully to do so anyway. Does anything stand out to any of you?:
<?php
echo "<h2>Edit Special Offer</h2><hr>";
if (isset($_COOKIE["username"]))
{
echo "Welcome " . $_COOKIE["username"] . "!<br />";
include "login.php";
}
else
echo "You need to log in to access this page.<br />";
if(isset($previous))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id < $id ORDER BY id DESC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($next))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id > $id ORDER BY id ASC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($add))
{
$query = "INSERT INTO special (specialtitle, specialinfo)
VALUES ('$specialtitle', '$specialinfo')";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Special Offer Added";
}
elseif (isset($update))
{
$query = "UPDATE special
SET specialtitle='$specialtitle', specialinfo='$specialinfo'
WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Monthly Special Updated";
}
elseif (isset($delete))
{
$query = "DELETE FROM special WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$specialtitle = "";
$specialinfo = "";
$message = "Special Offer Deleted";
}
$specialtitle = trim($specialtitle);
$specialinfo = trim($specialinfo);
?>
<form method="post" action="editspecial.php">
<p><b>Special Offer</b>
<br><input type="text" name="specialtitle" <?php echo "VALUE=\"$specialtitle\"" ?>> </p>
<p><b>Special Info/Description</b>
<br><textarea name="specialinfo" rows="8" cols="70" >
<?php echo $specialinfo ?>
</textarea> </p>
<br>
<input type="submit" name="previous" value="previous">
<input type="submit" name="next" value="next">
<br><br>
<input type="submit" name="add" value="Add">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<input type="hidden" name="id" <?php echo "VALUE=\"$id\"" ?>>
</form>
<?php
if (isset($message))
{
echo "<br>$message";
}
?>
Login.php:
<?php
function check_mysql()
{
if(mysql_errno()>0)
{
die ("<br>" . mysql_errno().": ".mysql_error()."<br>");
}
}
$dbh=mysql_connect ("xxxxxxxxxxxxxxxxx","xxxxxxxx","xxxxxxxx");
if (!$dbh)
{
die ("Failed to open the Database");
}
mysql_select_db("xxxxxx");
check_mysql();
if(!isset($id))
{
$id=0;
}
?>
Please please please do a little bit more learning before attempting to build this thing.
You can do it the way you are doing it, but with just a small amount of extra knowledge about OO programming, and maybe about the Pear db classes you will have 3x cleaner code.
If you really choose not to, at the very least, pull each of your save, update, delete, etc procedures out into functions instead of just inlining them in your code. put them in a separate file, and include it in that page.
It may not be useful to you, but I am going to dump a generic table access class here in the page for you. It requires a simple db class API, but if you use this or something like it your life will be 5x easier.
If you don't understand this code when you look at it, that's ok, but please just come back and ask questions about the stuff you don't understand. That is what stackoverflow is for.
This is an older class that should just do basic stuff. Sorry it's not better I just wanted to dig something out of the archives for you that was simple.
<?php
// Subclass this class and implement the abstract functions to give access to your table
class ActiveRecordOrder
{
function ActiveRecordOrder()
{
}
//Abstract function should return the table column names excluding PK
function getDataFields()
{}
//Abstract function should return the primary key column (usually an int)
function getKeyField()
{}
//abstract function just return the table name from the DB table
function getTableName()
{}
/*
This function takes an array of fieldName indexed values, and loads only the
ones specified by the object as valid dataFields.
*/
function loadRecordWithDataFields($dataRecord)
{
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
foreach($dataFields as $fieldName)
{
$this->$fieldName = $dataRecord[$fieldName];
}
}
function getRecordsByKey($keyID, &$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
$results = $dbHandle->select($tableName, $dataFields, array($keyField => $keyID));
return $results;
}
function search($whereArray, &$dbHandle)
{
$tableName = $this->getTableName();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
return $dbHandle->select($tableName, $dataFields, $whereArray);
}
/**
* Since it is *hard* to serialize classes and make sure a class def shows up
* on the other end. this function can just return the class data.
*/
function getDataFieldsInArray()
{
$dataFields = $this->getDataFields();
foreach($dataFields as $dataField)
{
$returnArray[$dataField] = $this->$dataField;
}
return $returnArray;
}
/**
* Added update support to allow to update the status
*
* #deprecated - use new function saveObject as of 8-10-2006 zak
*/
function updateObject(&$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateRow(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
/**
* Allows the object to be saved to the database, even if it didn't exist in the DB before.
*
* #param mixed $dbhandle
*/
function saveObject(&$dbhandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateOrInsert(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
}
"Welcome " . $_COOKIE["username"] . "!<br />"; [and many other places]
HTML-injection leading to cross-site security holes. You need to use htmlspecialchars every time you output a text value to HTML.
"INSERT INTO special (specialtitle, specialinfo) VALUES ('$specialtitle' [and many other places]
SQL-injection leading to database vandalism. You need to use mysql_real_escape_string every time you output a text value to an SQL string literal.
if (isset($_COOKIE["username"]))
Cookies are not secure, anyone can set a username cookie on the client-side. Don't use it for access control, only as a key to a stored or session user identifier.
You also appear to be using register_globals to access $_REQUEST values as direct variables. This is another extreme no-no.
Between all these security snafus you are a sitting duck for Russian hackers who will take over your site to push viruses and spam.
Be careful with your code there. Your not filtering your cookie value and you shouldn't be storing a username directly in there as it can be easily changed by the visitor. You should look into filter_input for filtering cookie data and eany form data that is being submitted - especially your $_POST['id']
this will save you a lot of heartache further down the line from attacks.
Your if else statements are checking if variables are set but you dont set next, previous, add etc
You are using submit buttons with those values so you would need to check for
if(isset($_POST['previous']))
instead of yours which is
if(isset($previous))
I can't see where you set your database details either unless you have an included file somewhere that you haven't posted. (don't post the real ones of course but i can't see anything)
I don´t know what's happening in login.php, but you're using $id before it is set. That´s just in the first part.
Edit: To clarify, you are using $id in every query statement and setting it afterwards, my guess would be that $id is null and that is why nothing gets returned.
Edit 2: What else is happening in login.php? If you never read your $_POST variables, nothing will ever happen.
Edit 3: Like I already partly said in a comment, your if(isset($previous)) section, elseif (isset($update)) section and elseif (isset($delete)) sections will never do anything as $id is always 0.
After authenticating your user you need to get and filter the posted variables, $_POST['id'], $_POST['previous'], etc.

Categories