I'm trying to do a website. I need to get all the reviews in the database. My initial guess was to use php like this:
function get_all_reviews(){
$db = dbConnection();
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
$statement = $db -> prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$name = $row["Nome"];
$title = $row["Title"];
$review = $row["Review"];
$email = $row["Email"];
?>
<div class="box" id="<?= $email ?>">
<div class="nome"><?= $name ?> dice:</div>
<div class="titolo"><?= $title ?> </div>
<div class="recensione"><?= $review ?> </div>
<button class="admin_bottom">X</button>
</div>
<?php
}
But since it's a project for the university, I need to not use it (it's mandatory). I need to send the request with jquery, then with php I should send the response with json, but I don't get how to recall the reviews and list them.
I try with this with php:
function gett_all_reviews(){
$db = dbConnection();
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
$statement = $db -> prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$resultSet = '{ ';
foreach ($result as $row) {
$resultSet .= '{"name": "'.$row["Nome"].'",';
$resultSet .= '"title": "'.$row["Title"].'",';
$resultSet .= '"review": "'.$row["Review"].'",';
$resultSet .= '"email": "'.$row["Email"].'"},';
}
$resultSet .= '}';
$db = null;
return $resultSet;
}
$s = get_all_reviews();
echo $s;
and with jquery:
$.getJSON( "../php/get_reviews.php", function( json ) {
for (let index = 0; index < json.length; index++) {
$("#conteiner_reviews").append(
"<div class=\"box\" id= \""+ json[index].email+ "\">"+
"<div class=\"nome\">"+json[index].name +" dice:</div>" +
"<div class=\"titolo\"><"+json[index].title+"</div>"+
"<div class=\"recensione\">"+json[index].review +"</div></div>");
}
});
But doesn't work.
function gett_all_reviews(){
$db = dbConnection();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT Nome as name, Title as title, reviews.Review as review, users.Email as email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
$statement = $db -> prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$db = null;
return $result;
}
echo json_encode(get_all_reviews());
$.getJSON('../php/get_reviews.php', function (data) {
$.each(data, function (item) {
$('#conteiner_reviews').append(
'<div class="box" id="' + item.email+ '">' +
'<div class="nome">' + item.name + 'dice:</div>' +
'<div class="titolo">' + item.title + '</div>' +
'<div class="recensione">' + item.review + '</div>'
);
});
});
Related
This snippet works only when I make a connection with PDO but I want it with mysqli.-->link
<?php
//fetch_comment.php
//$connect = new PDO('mysql:host=localhost;dbname=tbl_comment', 'root', '');
$connect = mysqli_connect('localhost','root','','tbl_comment');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
//
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"]);
echo $output;
}
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
.....
.....
...
?>
I tried to use mysqli fetch_all
$statement = $connect ->prepare("SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC");
$statement->execute();
$resultSet = $statement->get_result();
$result = $resultSet->fetch_all();
$output = '';
.....
$statement = $connect ->prepare("
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
");
$statement->execute();
$resultSet = $statement->get_result();
$result = $resultSet->fetch_all();
$count = $statement->num_rows();
$output = '';
but I am getting this messages:
Notice: Undefined index: comment_sender_name in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 46
Notice: Undefined index: date in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 46
Notice: Undefined index: comment in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 47
Notice: Undefined index: comment_id in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 48
Notice: Undefined index: comment_id in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 51
Update: Thanks to #Dharman when I use the MYSQLI_ASSOC it displays me the comments(first MySQL statement) but not the replies (second MySql statement).It worked on PDO. I also have a file to write a comment but when I change from PDO to mysqli it writes it two times in the database:
<?php
//add_comment.php
//$connect = new PDO('mysql:host=localhost;dbname=tbl_comment', 'root', '');
$connect=mysqli_connect('localhost','root','','tbl_comment');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
Just use $result = $resultSet->fetch_all(MYSQLI_ASSOC);
By default fetch_all returns numerical array, but you want an associative array. Pass the constant as an argument to fetch_all
I have an input form and I need to populate the autocomplete with data from a database. My approach seems to be working BUT I am pretty sure it's not the most efricient way. (I'm new to php, javascript)
Here's my code:
//get all organizations
$org_array = '';
$sql = "SELECT id, name FROM organizations";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
foreach ($results as $row) {
$sql = "SELECT id, name FROM organizations WHERE id = :id";
$stmt = $pdo->prepare($sql);
$id = $row['id'];
$stmt->bindValue(':id', $id);
$stmt->execute();
$org_id = $stmt->fetch(PDO::FETCH_ASSOC);
//echo $org_id['name'];
$org_array = $org_array . '"' . $org_id['name'] . '",';
}
}
And here is the JS part:
<input type="text" class="form-control autocompleteOrgs" name="newOrganization" id="newOrganization" aria-describedby="newOrganizationHelp" value="<?php echo
$my_profile['organization']; ?>">
<script>
$(function() {
var orgTags = [<?php echo $org_array ?>];
$(".autocompleteOrgs").autocomplete({
source: orgTags
});
});
</script>
You don't need to fetch organizations one more time, better approach would be:
$org_array = '';
$sql = "SELECT id, name FROM organizations";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
$org_array = implode(',', array_column($results, 'name'));
}
I'm doing my own little project converting UserCake (latest) to OOP with PDO, i've finalised a lot of features already. But right now i've been stuck for awhile on this Page functionality. So according to the code it's suppose to read the root folder for PHP files and add them to DB table (uc_pages) if they don't already exist. And if there's pages in the DB that doesn't exist in the root folder to delete those from the db.
I get no errors at all which is kinda interesting... but i'll post the code if anyone would be kind to give me a hand on this one.
Pages.php
<?php
require_once("resources/database.php");
$website_pages = new dbPages($db);
// set number of records per page
$records_per_page = 6;
// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;
$website_pages->getPageFiles();
//Retrieve list of pages in root usercake folder
$website_pages->fetchAllPages();
//Retrieve list of pages in pages table
$creations = array();
$deletions = array();
//Check if any pages exist which are not in DB
foreach ($website_pages->getPageFiles() as $web_page){
if(!isset($website_pages->readOne()[$web_page])){
$creations[] = $web_page;
}
}
//Enter new pages in DB if found
if (count($creations) > 0) {
$website_pages->create($creations);
}
if (count($website_pages->fetchAllPages()) > 0){
//Check if DB contains pages that don't exist
foreach ($website_pages->readOne() as $web_page){
if(!isset($website_pages->fetchAllPages()[$web_page['page']])){
$deletions[] = $web_page['id'];
}
}
}
//Delete pages from DB if not found
if (count($deletions) > 0) {
$website_pages->delete($deletions);
}
//Update DB pages
$website_pages->readAll($from_record_num, $records_per_page);
// header settings
$page_url="pages.php?";
$page_title = "UNFINISHED: All pages";
include_once "./resources/header.php";
?>
<div class='container'>
<div class='page-header'>
<h1><?php echo"{$page_title}";?></h1>
</div>
</div>
<div class="jumbotron">
<div class="container">
<?php
// query products
$stmt = $website_pages->readAll($from_record_num, $records_per_page);
$num = $stmt->rowCount();
// display the products if there are any
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<div class='col-xs-12 col-md-6'>
<div class='btn-group btn-group-justified' role='group'
aria-label='Justified button group'>
<a href='page.php?id={$id}' class='btn btn-warning' role='button'>
<span class='glyphicon glyphicon-edit'></span> Edit</a>
</div>";
echo "
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3 class='panel-title'>{$page_name}</h3>
</div>
<div class='panel-footer'>";
//Show public/private setting of page
if($private == 0){
echo "This page is Public";
}
else {
echo "This page is Private";
}
echo "</div></div></div>";
}
echo "</div>";
// needed for paging
$total_rows=0;
if($page_url=="pages.php?"){
$total_rows=$website_pages->countAll();
}
// paging buttons
include_once './resources/paging.php';
}
// tell the user there are no products
else{
echo "<div class=\"alert alert-danger alert-dismissable\">";
echo "<button type=\"button\" class=\"close\" data-
dismiss=\"alert\" aria-hidden=\"true\">×</button>";
echo "No pages found.";
echo "</div>";
}
echo "</div>";
?>
</div>
</div>
<?php require("./resources/footer.php")?>
Database.php
<?php
class Database{
// specify your own database credentials
private $host = "###########";
private $db_name = "website";
private $username = "###########";
private $password = "###########";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO(
"mysql:host=" . $this->host . ";dbname=" . $this->db_name,
$this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
require_once './resources/functions.php';
$website = new Configuration($db);
$website->readConfig();
?>
The part from functions.php that is struggling
class dbPages {
// database connection and table names
private $conn;
private $table_name = "uc_pages";
private $table_name2 = "uc_permission_page_matches";
// object properties
public $id;
public $page_id;
public $permission_id;
public $page_name;
public $private;
public $pages;
public $row;
public function __construct($db){
$this->conn = $db;
}
//Retrieve a list of all .php files in root files folder
function getPageFiles() {
$directory = "";
$pages = glob($directory . "*.php");
//print each file name
foreach ($pages as $web_page){
$row[$web_page] = $web_page;
}
return $row;
}
//Fetch information on all pages
function fetchAllPages() {
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . " ";
// prepare query statement
$stmt = $this->conn->prepare( $query );
$stmt->execute();
while ($stmt->fetch(PDO::FETCH_ASSOC)){
$row[$web_page] = array(
'id' => $id, 'page_name' => $page_name, 'private' => $private);
}
if (isset($row)){
return ($row);
}
}
// read products
function readAll($from_record_num, $records_per_page){
// select query
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . "
ORDER BY
page_name ASC
LIMIT
?, ?";
// prepare query statement
$stmt = $this->conn->prepare( $query );
// bind variable values
$stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
$stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);
// execute query
$stmt->execute();
// return values from database
return $stmt;
}
// used for paging products
public function countAll(){
$query = "SELECT COUNT(*) as total_rows
FROM " . $this->table_name . "";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row['total_rows'];
}
// used when filling up the update product form
function readOne(){
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . "
WHERE
page_name = ?
LIMIT
0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->id = $row['id'];
$this->page_name = $row['page_name'];
$this->private = $row['private'];
}
// create product
function create($pages){
//write query
$query = "INSERT INTO
" . $this->table_name . "
SET
id = ?,
page_name = ?,
private = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
$stmt->bindParam(2, $this->page_name);
$stmt->bindParam(3, $this->private);
foreach($pages as $page_name){
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
// delete the product
function delete($pages){
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
foreach($pages as $id){
if($result = $stmt->execute()){
return true;
}else{
return false;
}
}
$query2 = "DELETE FROM " . $this->table_name2 . "
WHERE page_id = ?";
$stmt2 = $this->conn->prepare($query);
$stmt2->bindParam(1, $this->page_id);
foreach($pages as $id){
if($result = $stmt2->execute()){
return true;
}else{
return false;
}
}
}
}
I have a php script which fill tables in my sql database. The problem is that it overwrites the tables each time I run it and I just want to add the datas at the end. I took inspiration from an existing script that I modify and I don't understand all it contains.
Here is my code :
<?php
try {
session_start();
require_once('./lib/demo/php/functions.php');
$db = getConnection();
$colMap = array(
0 => "LIBELLE",
1 => "DESCRIPTION",
2 => "CODE"
);
if (isset($_GET['data']) && $_GET['data']) {
$select = $db -> prepare('DELETE FROM COMPETENCES');
$select2 = $db -> prepare('DELETE FROM DESCRIPTION');
$select -> execute();
$select2 -> execute();
for ($r = 0, $rlen = count($_GET['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_GET['data'][$r]); $c < $clen; $c++) {
if (!isset($colMap[$c]) && !isset($colMap[$c])) {
continue;
}
$newVal = $_GET['data'][$r][$c];
$select = $db -> prepare('SELECT ID FROM COMPETENCES WHERE ID=? LIMIT 1');
$select2 = $db -> prepare('SELECT ID FROM DESCRIPTION WHERE ID=? LIMIT 1');
$select -> execute(array($rowId));
$select2 -> execute(array($rowId));
if ($row = $select->fetch() && $row = $select2->fetch()) {
$query = $db->prepare('UPDATE COMPETENCES SET `' . $colMap[$c] . '` = :newVal WHERE ID = :id');
$query2 = $db->prepare('UPDATE DESCRIPTION SET `' . $colMap[$c] . '` = :newVal2 WHERE ID = :id2');
} else {
$query = $db->prepare('INSERT INTO COMPETENCES (ID, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
$query2 = $db->prepare('INSERT INTO DESCRIPTION (ID, `' . $colMap[$c] . '`) VALUES(:id2, :newVal2)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query2->bindValue(':id2', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query2->bindValue(':newVal2', $newVal, PDO::PARAM_STR);
$query->execute();
$query2->execute();
}
}
}
$out = array(
'result' => 'ok'
);
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
}
I thought that remove the DELETE queries will fix the problem but the script doesn't work at all. I think the issue comes from the ids but I don't find where.
The datas are taken from a grid created with the javascript plugin Handsontable.
Can you help me please? I really need this script.
My script still doesn't work but I removed all what I found useless. Now, nothing happens at all in the database even if the new code seems to be more appropriate.
Here is the new :
<?php
try {
session_start();
require_once('./lib/demo/php/functions.php');
$db = getConnection();
mysql_set_charset('utf8', $db);
$colMap = array(
0 => 'LIBELLE',
1 => 'DESCRIPTION',
2 => 'CODE'
);
if (isset($_GET['data']) && $_GET['data']) {
for ($r = 0, $rlen = count($_GET['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_GET['data'][$r]); $c < $clen; $c++){
if (!isset($colMap[$c])) {
continue;
}
$newVal = $_GET['data'][$r][$c];
$query = $db->prepare('INSERT INTO COMPETENCES ("'.$colMap[$c].'") VALUES(:newVal)');
$query2 = $db->prepare('INSERT INTO DESCRIPTION ("'.$colMap[$c].'") VALUES(:newVal2)');
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query2->bindValue(':newVal2', $newVal, PDO::PARAM_STR);
$query->execute();
$query2->execute();
}
}
}
$out = array('result' => 'ok');
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
I created a script, social network. I have a problem. If a user uploaded a pic I should display the pic, if not then it should display the default pic. The problem is that every time I reload the page keeps on loading and the user pic doesn't display right. If I inspect the element, the pic url is correct but since the page keeps on loading, the pic doesn't display. I don't even have a loop only if the else statement. I tried for-each loop but same problem. Any help would be appreciated.
The function that I'm referring is profile_photo();
profile.php
<?php
session_start();
include_once('php/classes/db_config.php');
include_once('php/classes/class.user.php');
$user1 = new User($con);
$is_loggedin = (isset($_SESSION['uid']));
$is_uid = (!empty($_GET['uid']) && is_numeric($_GET['uid']));
//set uid
$def_uid = ($is_uid) ? $_GET['uid'] : $_SESSION['uid'];
// User valid check
// ### what does 1 mean, perhaps define a constant or use true/false instead
$user_valid = ($is_uid == true) ? $user1->check_user($def_uid) : 1;
// ## if $_SESSION['user'] doesn't exist these assignments will generate warnings
$name_id = $_SESSION['user']['uid'];
$name = $_SESSION['user']['uname'];
$fullname = $_SESSION['user']['fullname'];
$bio = $_SESSION['user']['bio'];
$time = date("Y-m-d H:i:s");
if (isset($_POST['logout'])) {
session_destroy();
header('Location: index.php');
exit;
}
if (isset($_POST['area_sub'])) {
if (empty($_POST['area'])) {
echo "<script>alert('Empty area field.')</script>";
}else {
$uid = $_GET['uid'];
if ($uid == '') {
$uid = $name_id;
}
$user1->post($name_id, $uid, $name, $_POST['area'], $time);
}
}
if($is_loggedin){
$sql = "SELECT * FROM follow_req WHERE user_two_req= :user_two_req";
$query = $con->prepare($sql);
$query->execute(array( ':user_two_req' => $name_id));
$result = $query->fetchALL(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Only Simple Albanian Social Network, with no ads</title>
<link rel="stylesheet" href="css/profile.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<?php if($is_loggedin !== true) {
include_once 'php/common/head.php'; ?>
<?php }?>
<?php
// If there is a propper UID available
if(($is_loggedin == true) || ($is_uid == true)) { ?>
<?php if ($is_loggedin == true){ ?>
<div id="menu">
<div id="menu_wrapper">
<div id="left_menu">
</div>
<div id="right_menu">
<div id='drop-zone'><?php
if($result == false){
echo "<h4 class='request'>0</h4>";
}else{
echo "<a href='#' class='request_more'>".count($result)."</a>";
}
?></div>
<form action='' method='post'>
<input type='hidden' name='logout' value='true' />
<input type='submit' name='submit' value='Logout' id='btn'>
</form>
</div>
</div>
</div>
<?php } ?>
<div id="profile_wrapper">
<div class="wrapper">
<div id="profile">
<?php
// If user is valid
if($user_valid == 1) {
// User is logged in user
if($def_uid == $_SESSION['uid']) {
include_once 'php/classes/profile_func.php';
}
include_once 'php/classes/user_info.php';
}else{?>
<h2>No Such User Exists</h2>
<h3>Please select a different user or <a href='index.php'>Login</a></h3>
<?php if($is_loggedin == true){ ?>
<h3>Go Back to My Profile</h3>
<?php
}
} ?>
<?php }else{?>
<h1>Invalid User</h1>
<h3>You must be Logged IN to see your profile OR you must select a profile (uid) to view.</h3>
<?php } ?>
</div>
</div>
</div>
<?php if($is_loggedin != true){ ?>
<div id="footer">
<h4>Per momentin vetem njerezit qe do perzgjidhen do kene akses.</h4>
<a href="#">
<div id="button">Kerkese Hyerje</div>
</a>
</div>
<?php } ?>
<script>
function LookUp(IdElem,URL){
$("#drop-zone").html('<div class="loader"></div>');
$.ajax({
url: URL,
cache: false,
success: function(result) {
$("#drop-zone").html(result);
}
});
}
$(document).ready(function() {
$("a.request_more").click(function(){
LookUp(this,'requests.php');
});
});
</script>
</body>
</html>
class.user.php
<?php
class User
{
public $db;
public $error;
public function __construct($con){
$this->db = $con;
}
/*** for login process ***/
public function check_login($username='', $password=''){
// Validate that your email is a real one
if(filter_var($username,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
$sql = "SELECT uid from users WHERE (uemail='$username' or uname='$username') and upass = '$password'";
$result = $this->db->Fetch($sql);
if ($result !== 0) {
// this login var will use for the session thing
$_SESSION['emailusername'] = $result[0]['uemail'];
$_SESSION['uid'] = $result[0]['uid'];
$_SESSION['user'] = $this->get_fullname($result[0]['uid'],0);
$_SESSION['login'] = true;
}
else
$this->error['Invalid Account'] = '<h3 id="error">Invalid Username or Password</h3>';
}
else
$this->error['Email'] = '<h3 id="error">Invalid Email Address</h3>';
return (!isset($_SESSION['emailusername']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid, $write = 1){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$user_data = $this->db->Fetch($sql);
if($user_data !== 0) {
$user['uname'] = $user_data[0]['uname'];
$user['fullname'] = $user_data[0]['fullname'];
$user['uemail'] = $user_data[0]['uemail'];
$user['uid'] = $user_data[0]['uid'];
$user['bio'] = $user_data[0]['bio'];
// This gives the option of returning an array (setting session array) or echoing
if($write == 1)
echo implode("<br />",$user);
else
return $user;
}
}
public function check_user($uid){
$sql = "SELECT * from users WHERE uid= :uid ";
$q = $this->db->prepare($sql);
$q->execute(array(':uid'=>$uid));
return $q;
}
/*** starting the session ***/
public function get_session()
{
return $_SESSION['login'];
}
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
public function check_req($is_uid, $def_uid){
$sql = "SELECT * from follow_req WHERE user_one_req = :user_one_req AND user_two_req = :user_two_req";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one_req'=>$is_uid, 'user_two_req'=>$def_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function insert($is_uid, $def_uid){
$sql = "INSERT INTO follow_req (user_one_req, user_two_req) VALUES (:user_one_req, :user_two_req)";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one_req'=>$is_uid, ':user_two_req'=>$def_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function delete($is_uid, $def_uid){
$sql = "DELETE FROM follow_req WHERE user_one_req = :user_one_req AND user_two_req = :user_two_req";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one_req'=>$is_uid, ':user_two_req'=>$def_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function checkimg($img_id){
$sql = "SELECT * from users WHERE img_id = '$img_id'";
$result = $this->db->Fetch($sql);
$count_row = ($result !== 0)? count($result): 0;
}
public function img($img_id, $part){
$sql = "UPDATE users SET img_id='$img_id', image='$part' WHERE uid=".$_SESSION['uid']."";
$q = $this->db->prepare($sql);
$q -> execute(array(':img_id'=>$img_id, ':image'=>$part));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function check_friends($is_uid, $def_uid){
$sql = "SELECT * from follow WHERE (user_one = :user_one AND user_two = :user_two) OR (user_one = :user_two AND user_two = :user_one)";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one'=>$is_uid, ':user_two'=>$def_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function del_friends($is_uid, $def_uid){
$sql = "DELETE FROM follow WHERE (user_one = :user_one AND user_two = :user_two) OR (user_one = :user_two AND user_two = :user_one)";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one'=>$is_uid, ':user_two'=>$def_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function checking($def_uid, $is_uid){
$sql = "SELECT * from follow_req WHERE user_one_req = :user_one_req AND user_two_req = :user_two_req";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one_req'=>$def_uid, ':user_two_req'=>$is_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function accept_req($def_uid, $is_uid){
$sql = "INSERT INTO follow ( user_one, user_two) VALUES ( :user_one, :user_two)";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one'=>$def_uid, ':user_two'=>$is_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function delete_req($def_uid, $is_uid){
$sql = "DELETE FROM follow_req WHERE user_one_req = :user_one_req AND user_two_req = :user_two_req";
$q = $this->db->prepare($sql);
$q -> execute(array(':user_one_req'=>$def_uid, ':user_two_req'=>$is_uid));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
return $result;
}
public function post($a_id='', $r_id='', $name, $area='', $time){
$sql = $this->db->prepare("INSERT INTO post (user_id, rec_id, user, area, time) VALUES ( ?, ?, ?, ?, ?)");
$sql -> bindParam(1, $a_id);
$sql -> bindParam(2, $r_id);
$sql -> bindParam(3, $name);
$sql -> bindParam(4, $area);
$sql -> bindParam(5, $time);
$sql -> execute();
}
public function profile_photo($name_id){
$sql = "SELECT * FROM users WHERE img_id= :img_id";
$q = $this->db->prepare($sql);
$q->execute(array(':img_id'=>$name_id));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
if($result[0]['img_id'] == $name_id){
echo "<img id='profile_img' src='test/upload/".$name_id."_".$result[0]['image']."'/>";
}else{
echo "<img id='profile_img' src='classversiondontdelete/images/default/profile_icon.gif'/>";
}
return $result;
}
public function getResults(){
if($_GET['uid'] == ''){
$result = $this->db->Fetch("SELECT * FROM post WHERE rec_id = ".$_SESSION['uid']." ");
}else if($_GET['uid'] == 0){
$result = $this->db->Fetch("SELECT * FROM post WHERE rec_id = ".$_SESSION['uid']." ");
}else{
if(is_numeric($_GET['uid']))
$result = $this->db->Fetch("SELECT * FROM post WHERE rec_id = '".$_GET['uid']."'");
}
if(is_array($result)){
}
}
}
?>
Solved. My mistake was:
public function profile_photo($name_id){
$sql = "SELECT * FROM users WHERE img_id= :img_id";
$q = $this->db->prepare($sql);
$q->execute(array(':img_id'=>$name_id));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
if($result[0]['img_id'] == $name_id){
echo "<img id='profile_img' src='test/upload/".$name_id."_".$result[0]['image']."'/>";
}else{
echo "<img id='profile_img' src='classversiondontdelete/images/default/profile_icon.gif'/>";
}
return $result;
}
I should have put $_SESSION instead of $name_id
public function profile_photo($name_id){
$sql = "SELECT * FROM users WHERE img_id= :img_id";
$q = $this->db->prepare($sql);
$q->execute(array(':img_id'=>$name_id));
$result = $q->fetchALL(PDO::FETCH_ASSOC);
if($result[0]['img_id'] == $_SESSION['uid']){
echo "<img id='profile_img' src='test/upload/".$name_id."_".$result[0]['image']."'/>";
}else{
echo "<img id='profile_img' src='classversiondontdelete/images/default/profile_icon.gif'/>";
}
return $result;
}