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;
}
Related
Hi i have an address book I added the possibility of add a photo.
This is the function for view Name,Surname,Email and telephone
// Display users
public function display(){
$temp_arr = array();
$res = $this->db->run("SELECT * FROM users ORDER by cognome,nome ");
$count=$this->db->rowCount();
while($row = $this->db->fetchArray()) {
$temp_arr[] =$row;
}
return $temp_arr;
}
<?php
$data = $user->display();
$i = 0;
foreach( $data as $eachrecord ) {
$i++;
?>
my idea was to do so how do i implement it?
$sql = "SELECT name FROM upload where id=$id";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image = $row['name'];
$image_src = "uploads/".$image;
<td><img src='<?php echo $image_src; ?>' ></td>
to take id use this function
// get id upload
public function getid(){
$db = new mysqli("localhost","root","", "rubrica");
if ($db-> connect_errno) {
exit();
}
$nome = $this->unome;
$cognome = $this->ucognome;
$email = $this->uemail;
$telefono = $this->utel;
$query = $db->query("SELECT id FROM users WHERE nome='$nome' and cognome='$cognome' and email='$email' and telefono='$telefono'");
$id = $query->fetch_assoc()['id'];
$db->close();
return $id;
}
thank you in advance who will help me!
<?php
// Post variables
$post_id = 0;
$isEditingPost = false;
$published = 0;
$title = "";
$post_slug = "";
$body = "";
$featured_image = "";
$post_topic = "";
/* - - - - - - - - - -
- Post functions
- - - - - - - - - - -*/
// get all posts from DB
function getAllPosts()
{
global $conn;
// Admin can view all posts
// Author can only view their posts
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
} elseif ($_SESSION['user']['role'] == "Author") {
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
$result = mysqli_query($conn, $sql);
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
$final_posts = array();
foreach ($posts as $post) {
$post['author'] = getPostAuthorById($post['user_id']);
array_push($final_posts, $post);
}
return $final_posts;
}
// get the author/username of a post
function getPostAuthorById($user_id)
{
global $conn;
$sql = "SELECT username FROM users WHERE id=$user_id";
$result = mysqli_query($conn, $sql);
if ($result) {
// return username
return mysqli_fetch_assoc($result)['username'];
} else {
return null;
}
}
?>
If both of these conditions fail:
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
} elseif ($_SESSION['user']['role'] == "Author") {
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
$result = mysqli_query($conn, $sql);
Then the $sql variable is undefined. If you have to have them this way, then you can check if it's set and return a default value.
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
} elseif ($_SESSION['user']['role'] == "Author") {
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
if(!isset($sql)) return false; //or [] if you want the type to stay an array.
$result = mysqli_query($conn, $sql);
Or something like that, depending on your needs.
You could also return an error:
}else{
return new WP_Error( 'restricted', __( "Not an Admin or Author", "my_textdomain" ) );
}
https://codex.wordpress.org/Class_Reference/WP_Error
Basically this $_SESSION['user']['role'] is neither an Admin nor an Author. one thing to note is string matches are case sensitive.
So I've been stuck on this for quite a while, surprisingly the update and delete functions work just fine, however I cannot make the CREATE function work properly. Please have a look at it and tell me what I'm doing wrong
<-------------- Entire model for admin panel-------------->>>>>>>> Connection to DB is working fine---------->>>>>>>>>>>
<?php
include_once "Model.php";
class ModelPages extends Model {
public function get($key) {
$sql = "SELECT * from pages where page_key = '$key'";
$row = '';
$page = Null;
foreach ($this->pdo->query($sql) as $row) {
$page = $row;
}
// echo "<pre>";
// var_dump($page);
// exit;
return $page;
}
public function getAll() {
$statement = $this->pdo->prepare("SELECT * from pages Where Id > 3");
$result = $statement->execute();
$pages = array();
if($result) {
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
}
return $pages;
}
public function updatePage($params=array()) {
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$pageId = isset($params['page_key']) ? $params['page_key'] : null;
$pageTitle = isset($params['page_title']) ? $params['page_title'] : null;
$pageBody = isset($params['page_body']) ? $params['page_body'] : null;
if ($pageId == null) {
return 'No page id provided';
}
$sql = "UPDATE " . $tableName . " SET
title = :title,
body = :body
WHERE page_key = :page_key";
$statement = $this->pdo->prepare($sql);
$statement->bindParam(':title', $pageTitle, PDO::PARAM_STR);
$statement->bindParam(':body', $pageBody, PDO::PARAM_STR);
$statement->bindParam(':page_key', $pageId, PDO::PARAM_INT);
$result = $statement->execute();
return $result;
}
public function deletePage($pageId) {
// build sql
$sql = "DELETE FROM pages WHERE id = " . intval($pageId);
$statement = $this->pdo->prepare($sql);
$result = $statement->execute();
return $result;
}
public function createPage($params=array()){
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$page_key = isset($params['page_key']) ? $params['page_key'] : 'page_key';
$pageTitle = isset($params['page_title']) ? $params['page_title'] : 'page_title';
$pageBody = isset($params['page_body']) ? $params['page_body'] : 'page_body';
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
// prepare query for execution
$statement = $this->pdo->prepare($sql);
// bind the parameters
$statement->bindParam(':page_key', $_POST['page_key']);
$statement->bindParam(':title', $_POST['title']);
$statement->bindParam(':body', $_POST['body']);
// specify when this record was inserted to the database
// Execute the query
$result = $statement->execute();
return $result;
}
}
<?php
include 'controllers/controller.php';
include 'models/Model.php';
include 'models/ModelPages.php';
<------------------------ADMIN CONTROller----------------------->>>>>>>>>>>>
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
// TODO: update DB
$tableData['page_body'] = $_POST['body'];
$tableData['table'] = 'pages';
$tableData['page_title'] = $_POST['title'];
$tableData['page_key'] = $_POST['page_key'];
$response = $ModelPages->updatePage($tableData);
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&success=true");
}
}
if(isset($_GET['page_key'])) {
// by default we assume that the key_page exists in db
$error = false;
$page = $ModelPages->get($_REQUEST['page_key']);
// if page key does not exist set error to true
if($page === null) {
$error = true;
}
// prepare data for the template
$data = $page;
$data["error"] = $error;
// display
echo $this->render2(array(), 'header.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2($data, 'admin_update_page.php');
echo $this->render2(array(), 'footer.php');
} else {
// case: delete_page
if(isset($_GET['delete_page'])) {
$response = $ModelPages->deletePage($_GET['delete_page']);
if($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&deleted=true");
}
}
}
//Get table name and make connection
if(isset($_POST['submit'])) {
$page_key = $_POST['page_key'];
$page_title = $_POST['title'];
$page_body = $_POST['body'];
$response = $ModelPages->createPage();
if($response=TRUE){
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&created=true");
}
}
}
// load all pages from DB
$pages = $ModelPages -> getAll();
// display
echo $this->render2(array(), 'header_admin.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2(array("pages"=> $pages), 'admin_view.php');
echo $this->render2(array(), 'footer.php');
}
}
?>
Since you have if(isset($_POST['page_key']) on the top:
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
...
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?
}
and it is used to call $response = $ModelPages->updatePage($tableData);
your code never reach the part with good values at the bottom:
if(!isset($_POST['page_key'])) {
...
$response = $ModelPages->createPage($tableData);
So my simple but not the best suggestion is use extra parameter when POST like action. so you can check:
if(isset($_POST['action']) && $_POST['action']=='update') {
...
} elseif (isset($_POST['action']) && $_POST['action']=='create') {
...
} etc...
hope this will help you for now :-)
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
$tablename is not in scope when the statement above is executed. And you've got no error handling in the code.
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 need help with this code, i need it to add an array in Gangs
under members and seperate them with -
I need every member in the Gang to be listed under Members and separated with -
so i can explode them below.
This is the line that adds the members to gangs but its without - and i think it erases members that are already there.
$result = mysql_query("UPDATE Gangs SET members='".$name."'WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'")
or die(mysql_error());
full code
if(isset($_POST['creategang'])){
if(empty($_POST['gang_name'])){
echo "Enter a Gang Name.";
} else {
if (strlen($_POST['gang_name']) > "20"){
echo "The username may not consist out of more then 20 characters.";
}else{
if (ereg('[^A-Za-z0-9]', $_POST['gang_name'])) {
echo "Invalid Name only A-Z,a-z and 0-9 is allowed.";
}else{
$sql = "SELECT name FROM Gangs WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This name has already been used.!';
}else{
$sql = "INSERT INTO Gangs SET name = '".$_POST['gang_name']."' , owner= '$name'";
$res = mysql_query($sql);
$result = mysql_query("UPDATE users SET gang='".mysql_real_escape_string($_POST['gang_name'])."' WHERE id='" .mysql_real_escape_string($_SESSION['user_id']). "'")
or die(mysql_error());
$result = mysql_query("UPDATE Gangs SET members='".$name."'WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'")
or die(mysql_error());
echo 'Gang successfully created!';
}
}
}
}
}
?>
this is the code i will use to separate the array
$Gang_array = explode("-", $Gang_members);
Thanks for viewing my question and thanks in advance for helping me
new code to add to gang
<? include_once("connect.php"); ?>
<?
if(isset($_SESSION['user_id'])) {
// Login OK, update last active
$sql = "UPDATE users SET lastactive=NOW() WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'";
mysql_query($sql);
}else{
header("Location: index.php");
exit();
}
$sql = "SELECT * FROM users WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$id = htmlspecialchars($row->id);
$userip = htmlspecialchars($row->userip);
$name = htmlspecialchars($row->name);
$sitestate = htmlspecialchars($row->sitestate);
$password = htmlspecialchars($row->password);
$mail = htmlspecialchars($row->mail);
$money = htmlspecialchars($row->money);
$exp = htmlspecialchars($row->exp);
$rank = htmlspecialchars($row->rank);
$health = htmlspecialchars($row->health);
$points = htmlspecialchars($row->points);
$profile = htmlspecialchars($row->profile);
$gang = htmlspecialchars($row->gang);
?>
<?php
$sql = "SELECT * FROM Gangs WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$Gang_name = htmlspecialchars($row->name);
$Gang_owner = htmlspecialchars($row->owner);
$Gang_money = htmlspecialchars($row->money);
$Gang_exp = htmlspecialchars($row->exp);
$Gang_level = htmlspecialchars($row->level);
$Gang_members = htmlspecialchars($row->members);
$Gang_array = explode("-", $Gang_members);
$Gang_profile = htmlspecialchars($row->profile);
?>
<div id="content" class="profile">
<h2>Gang Profile</h2>
<form method="post" >
<input type="submit" name="Petition" id="Petition" value="Petition">
</form>
<center>
<h1><?php echo $Gang_name; ?></h1>
Owner: <?php echo $Gang_owner; ?><br>
Gang Cash: $<?php echo $Gang_money; ?><br>
Gang Exp: <?php echo $Gang_exp; ?><br>
Gang Level: <?php echo $Gang_level; ?><br>
Gang Members: <?php echo $Gang_array; ?><br>
</center><br>
<p>Gang Quote</p>
<div id="UserText">
<?php
$Gang_profile = htmlentities($Gang_profile);
$Gang_profile = nl2br($Gang_profile);
$Gang_profile = stripslashes($Gang_profile);
echo $Gang_profile; ?>
</div>
</div>
<?
if (isset($_POST['Petition'])) {
$result = mysql_query("SELECT members FROM Gangs
WHERE name='".$Gang_name."'");
if ($result) {
while($row = mysql_fetch_assoc($result)) {
$members = $row['members'];
}
}
if ($members != '') $members .= '-'.$name;
else $members = $name;
$result = mysql_query("UPDATE Gangs SET members='".$members."' WHERE name='".$Gang_name."'");
}
If I understand your question correctly. You can try this :
Get the members first :
$result = mysql_query("SELECT members FROM Gangs
WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'");
if ($result) {
while($row = mysql_fetch_assoc($result)) {
$members = $row['members'];
}
}
Then add new member and do update :
//This is to check whether $name is already in the gangs
if (strpos($members,$name) !== false) {
if ($members != '') $members .= '-'.$name;
else $members = $name;
//Update to gangs
$result = mysql_query("UPDATE Gangs SET members='".$members."' WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'");
}
else sprintf("%s is in the gangs already",$name);
Hope it helps.
Pseudo code, but this should probably work:
$result = mysql_query("UPDATE Gangs SET members = members + '-' + '".$name."'WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'")
or die(mysql_error());