OOP PHP PDO, Page function doesn't work (UserCake) - php

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;
}
}
}
}

Related

How do I fix Fatal error: Uncaught ArgumentCountError?

I made this product class which do CRUD operations in database I error in constructor method:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Products::__construct(), 0 passed.
I am trying to save, get, update and delete products from table and uploading one image file to database along with other variables. How do i upload image along it? is my script right?
I tried to skip constructor method to see if other methods works on its own but it wont happen
<?php
error_reporting(E_ALL);
class Products {
public $id;
public $cat_id;
public $name;
public $description;
public $supportedFormats = ['image/png' ,'image/jpeg' ,'image/jpg', 'image/gif'];
public $price;
// Constructor
function __construct($id, $cat_id, $name, $description,$supportedFormats, $price)
{
$this->id = $id;
$this->cat_id = $cat_id;
$this->name = $name;
$this->description = $description;
$this->supportedFormats = $supportedFormats;
$this->price = $price;
}
// Method to show output
function __toString()
{
$output = "<h2> Product id: $this->id</h2> \n " . "<h2> Category id : $this->cat_id </h2> \n" . "<h2> Name : $this->name</h2> \n" . "<h2>Product description: $this->description </h2> \n" ."<h2> Image: $this->supportedFormats". "<h2> Price : $this->price </h2> \n" ;
return $output;
}
// Method for saving product to database
function saveProduct()
{
$con = mysqli_connect("localhost", "root", "root", "my_shop");
$query = "INSERT INTO products VALUES (?,?,?,?,?,?)";
$stmt = $con->prepare($query);
$stmt->bind_param("iissbd", $this->id, $this->cat_id, $this->name, $this->description, $this->supportedFormats, $this->price);
$result = $stmt->execute();
if ($_FILES)
{
$img = $_FILES['filename']['image'];
move_uploaded_file($_FILES['filename']['tmp_name'], $img);
echo "Uploaded image '$img'<br><img src='$img'>";
}
// $img = move_uploaded_file($supportedFormats, 'includes/');
$con->close();
return $result;
}
// Method to update products from database
function updateProduct()
{
$con = mysqli_connect("localhost", "root", "root", "my_shop");
$query = "UPDATE products SET id = ? , cat_id = ?, name = ?, description = ?, supportedFormats = ?, price = ?" . "WHERE id = $this->id";
$stmt = $con->prepare($query);
$stmt->bind_param("iissbd", $this->id, $this->cat_id, $this->name, $this->description, $this->supportedFormats, $this->price);
$result = $stmt->execute();
if ($_FILES)
{
$img = $_FILES['filename']['image'];
move_uploaded_file($_FILES['filename']['tmp_name'], $img);
echo "Uploaded image '$img'<br><img src='$img'>";
}
// $img = move_uploaded_file($supportedFormats, 'includes/');
$con->close();
return $result;
}
// Method to remove product from table
function removeProduct()
{
$con = mysqli_connect("localhost", "root", "root", "my_shop");
$query = "DELETE FROM products WHERE id = $this->id";
$result = $con->query($query);
$con->close();
return $result;
}
// Method to get all products
static function getProduct()
{
$con = mysqli_connect("localhost", "root", "root", "my_shop");
$query = "SELECT * FROM products";
$result = $con->query($query);
if (mysqli_num_assoc($result) > 0)
{
$products = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$product = new Product($row['id'],$row['cat_id'],$row['name'],$row['description'],$row['supportedFormats'],$row['price']);
array_push($products, $product);
unset($product);
}
$con->close();
return $result;
}
else
{
$con->close();
return NULL;
}
}
// Method to find bidders
static function findProducts()
{
$con = mysqli_connect("localhost", "root", "root", "my_shop");
$query = "SELECT * FROM products WHERE id = $id";
$result = $con->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($row)
{
$product = new Product($row['id'],$row['cat_id'],$row['name'],$row['description'],$row['supportedFormats'],$row['price']);
$con->close();
return $result;
}
else
{
$con->close();
return NULL;
}
}
}
// $prod1 = new Products();
// echo findProducts();
?>
I expect it perform crud functionality in database
The class does not have to contain a constructor. However, when the class has a constructor, when creating objects, you must specify the arguments that will be sent to the constructor.

Incorporate INSERT Mysql query for MVC controller in PHP

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.

Page keeps on loading. PHP

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;
}

Issues in printing out php array

Unfortunately I am struggling to print some array items in PHP and was hoping someone could assist me. Slightly embarassing :) I think I might be using arrays incorrectly? I am trying to build an application object from the database and once this has been done i am trying to iterate over it and print some basic details. I have also included the separate Application class.
<?php
include("application.php");
$applicationsForUser = array();
if(isset($_POST['submit'])){
$username=$_POST["username"];
$password=$_POST["password"];
$userid = logUserIn($username, $password);
if($userid > 0){
getAppInformation($userid);
foreach ($applicationsForUser as $app) {
echo $app->$getUserid() . $app->$getName();
}
}
}
function getAppInformation($userid){
$conn = new mysqli('localhost:3306', 'root', '', 'clientportal');
if ($conn->connect_errno > 0) {
die('Could not connect: ' . mysql_error());
}else{
//we have connected to the database
$sql = "SELECT * FROM application WHERE userid = '$userid'";
if(!$val = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}else{
$index = 0;
while($row = $val->fetch_assoc()){
$userid = $row['userid'];
$name = $row['name'];
$dateCreated = $row['date'];
$invoice = $row['invoiceid'];
$comment = $row['commentsid'];
$application = new Application($userid, $name, $dateCreated, $invoice, $comment);
$applicationsForUser[$index] = $application;
$index++;
}
}
}
$conn -> close();
}
<?php
class Application {
var $userid;
var $name;
var $dateCreated;
var $invoice;
var $comment;
function Application($userid, $name, $dateCreated, $invoice, $comment) {
$this ->userid = $userid;
$this ->name = $name;
$this ->dateCreated = $dateCreated;
$this ->invoice = $invoice;
$this ->comment = $comment;
}
function getUserid(){
return $this ->userid;
}
function getName(){
return $this ->name;
}
function getDateCreatd(){
return $this ->dateCreated;
}
function getInvoice(){
return $this ->invoice;
}
function getComment(){
return $this ->comment;
}
}
?>
Your problem is, that $applicationsForUser is supposed to be global. Therefore you need to use
function getAppInformation($userid){
global $applicationsForUser;
Otherwise your foreach iterates over an empty array here:
getAppInformation($userid);
foreach ($applicationsForUser as $app) {
Don't use globals:
You didn't initialize your array before trying to loop through it.
<?php
include("application.php");
if(isset($_POST['submit'])){
$username=$_POST["username"];
$password=$_POST["password"];
$userid = logUserIn($username, $password);
if($userid > 0){
// get application information
$applicationsForUser = getAppInformation($userid);
foreach ($applicationsForUser as $app) {
echo $app->$getUserid() . $app->$getName();
}
}
}
function getAppInformation($userid){
$applicationsForUser = array();
$conn = new mysqli('localhost:3306', 'root', '', 'clientportal');
if ($conn->connect_errno > 0) {
die('Could not connect: ' . mysql_error());
}else{
//we have connected to the database
$sql = "SELECT * FROM application WHERE userid = '$userid'";
if(!$val = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}else{
$index = 0;
while($row = $val->fetch_assoc()){
$userid = $row['userid'];
$name = $row['name'];
$dateCreated = $row['date'];
$invoice = $row['invoiceid'];
$comment = $row['commentsid'];
$application = new Application($userid, $name, $dateCreated, $invoice, $comment);
$applicationsForUser[$index] = $application;
$index++;
}
}
}
$conn -> close();
return $applicationsForUser;
}

How to use multiple queries in one php function

Hi all i was just wondering how I would get a php function to run two sql queries my function at the moment is the code below the connection to the database is at the top of the page so I don't need to right the connection every time my full page code is :
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT subject.subject_id,subject.description,COUNT(media.subject_id) as media_count\n"
. "from subject LEFT OUTER JOIN media ON subject.subject_id = media.subject_id \n"
. "WHERE verified = 1\n"
. "GROUP BY subject.subject_id,subject.description ORDER BY subject.description ";
$res = mysql_query($sql,$this->conn);
$category = '<option value="%">Subject</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description']. '...('.$row['media_count'].')</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT section.section_id,section.description,section.subject_id,COUNT(media.section_id) as media_count
FROM section LEFT OUTER JOIN media ON section.section_id = media.section_id
AND section.subject_id = media.subject_id
WHERE section.subject_id={$_POST['id']} AND verified = 1
GROUP BY section.section_id,section.description";
$res = mysql_query($sql,$this->conn);
$type = '<option value="%">choose...';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description']. '...('.$row['media_count'].') </option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT principle.principle_id,principle.description,principle.section_id,COUNT(media.principle_id) as media_count
FROM principle
LEFT OUTER JOIN media ON principle.principle_id = media.principle_id
AND principle.section_id = media.section_id
WHERE principle.section_id={$_POST['id']} AND verified = 1
GROUP BY principle.principle_id,principle.description";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="%">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description']. '...('.$row['media_count'].') </option>';
}
return $principle;
}
public function GetResults()
{
//$vars = $_POST["comboboxselections"]; // this gets comboboxselections from index.php
list($subjectID, $sectionID, $principleID) = explode('#', $_POST["comboboxselections"]);
$box = ""; // placeholder for the html results to be returned to
$sql = "SELECT media_id,title,blurb
FROM media
WHERE subject_id = $subjectID AND section_id = $sectionID AND principle_id= $principleID AND verified = 1"; // sql query
$hasprintedrecords = false; // capture records if there are no records printed to screen
$res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
{
$hasprintedrecords = true;// if there are records this equals true if not equals false
$box .= '
<div style="margin-top:5px;height:120px;padding:0px;"id="Video">
<div style="width:185px;height:105px;float:left;" id="VideoImage">
<img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
</div>
<div style="float:right;padding-left:5px;width:72%;font-size:15px;padding-top:0px;font:verdana,sans-serif;" id="text">
<div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
<a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a>
<div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
<div id="Downloads">
<a href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">
<img style="width:100px; margin-left:-10px;margin-top:10px;" src="images/download.jpg">
</a>
</div>
</div>
</div>'; // if results are available then display to screen
}
if ( $hasprintedrecords == false) // if there are no results then function below is run
{
$box .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen
}
return $box; // returns results to the screen
}
public function ShowJobRole() {
$sql = "SELECT jobrole_id,description
FROM jobrole ";
$res = mysql_query($sql,$this->conn);
$jobrole = '<option value="%">Job role</option>';
while($row = mysql_fetch_array($res))
{
$jobrole .= '<option value="' . $row['jobrole_id'] . '">' . $row['description'] . '...('.$row['media_count'].'</option>';
}
return $jobrole;
}
public function ShowCareer() {
$sql = "SELECT career_id,description FROM career WHERE jobrole_id={$_POST['id']}";
$res = mysql_query($sql,$this->conn);
$career = '<option value="%">Career</option>';
while($row = mysql_fetch_array($res))
{
$career .= '<option value="' . $row['career_id'] . '">' . $row['description'] . '</option>';
}
return $career;
}
public function get_job () {
//$vars1 = $_POST["comboboxselections1"]; // this gets comboboxselections from index.php
list($jobroleID, $careerID) = explode('#', $_POST["comboboxselections1"]);
$res = mysql_query($sql,$this->conn);
$box = ""; // placeholder for the html results to be returned to
$sql = "SELECT title,blurb,m.media_id
FROM media_career_crossref mcc
INNER JOIN media m ON m.media_id = mcc.media_id
WHERE mcc.jobrole_id = $jobroleID AND mcc.career_id = $careerID";
$hasprintedrecords = false; // capture records if there are no records printed to screen
$res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
{
$hasprintedrecords = true;// if there are records this equals true if not equals false
$box .= '
<div style="margin-top:5px;height:120px;padding:0px;"id="Video">
<div style="width:185px;height:105px;float:left;" id="VideoImage">
<img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
</div>
<div style="float:right;padding-left:5px;width:72%;font-size:15px;padding-top:0px;font:verdana,sans-serif;" id="text">
<div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
<a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a>
<div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
<div id="Downloads">
<a style="width:100px; margin-left:-10px;margin-top:10px;" href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">
<img style="width:110px;" src="images/download.jpg">
</a>
</div>
</div>
</div>'; // if results are available then display to screen
}
if ( $hasprintedrecords == false) // if there are no results then function below is run
{
$box .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen
}
return $box; // returns results to the screen
}
public function Unverified()
{
$unverified = "";
$sql = "SELECT *
FROM media
WHERE verified = 0 "; // sql query
$box = "";
$hasprintedrecords = false; // capture records if there are no records printed to screen
$res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
{
$hasprintedrecords = true;// if there are records this equals true if not equals false
$unverified .= '
<div style="margin-top:5px;height:120px;padding:0px;"id="Video">
<div style="width:185px;height:105px;float:left;" id="VideoImage">
<img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
</div>
<div style="float:right;padding-left:5px;width:72%;font-size:12px;padding-top:0px;font:verdana,sans-serif;" id="text">
<div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
<a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a>
<div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
<div id="Downloads">
<a id="Download" href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">Download</a>
</div>
</div>
</div>'; // if results are available then display to screen
}
if ( $hasprintedrecords == false) // if there are no results then function below is run
{
$unverified .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen
}
return $unverified; // returns results to the screen
}
public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) {
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
$this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
mysql_query($sql, $this->conn);
(return mysql_affected_rows($this->conn) > 0);
}
public function addMediaCrossRef($Job, $Career, $Uniq_id) {
$sql = "INSERT INTO media_career_crossref (media_id, jobrole_id, career_id, verified, media_uniqid)
VALUES (NULL, '".$Job."', '".$Career."', '0', '".$Uniq_id."')";
mysql_query($sql, $this->conn);
(return mysql_affected_rows($this->conn) > 0);
}
}
$opt = new SelectList();
?>
above is the full code that I have currently got for this web page the latest functions are the last on the page.
this is how the functions are being called from a different page
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
include "select.class.php";
/*$opt->addNewMediaCrossRef($Job, $Career, $Uniq_id);*\ /* me trying to call both functions at once this didnt work either*/
$opt->addNewRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id);
}
any help would be much appreciated
The other answer might have stated that you can use MySQLi's multiquery option, and also as I commented you can use *_query() once for the first statement and second time for the second statement. However, you are braking the single responsibility principle of the method. If you want to chain to actions within one, separate them in different methods and call inwithin.
public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) {
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
$this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
return yourQueryFunction($sql, $this->conn);
}
public function addMediaCrossRef($Job, $Career, $Uniq_id) {
$sql = "INSERT INTO media_career_crossref (media_id, jobrole_id, career_id, verified, media_uniqid)
VALUES (NULL, '".$Job."', '".$Career."', '0', '".$Uniq_id."')";
return yourQueryFunction($sql, $this->conn);
}
And normally methods do not return the query() return value, especially when they are insert/update
I would prefer:
public function addNewMediaRecord($all_the_params) {
$sql = ".....";
yourQueryFunction($sql);
$this->chainedMethod($params);
return yourFunctionforAFFECTED_ROWS() > 0;
}
So it will return boolean if affected rows are more than zero (successful insert).
Also you'd better wrap the database functions in order to have easier switch between libraries, when you need to.
E.g.:
class Database {
private $_host;
private $_user;
private $_pass;
private $_db;
private $_conn;
public function __construct($host, $user, $pass, $db) {
$this->_host = $host;
$this->_user = $user;
$this->_pass = $pass;
$this->_db = $db;
$this->connect();
}
private function connect() {
$this->_conn = mysqli_connect($this->_host, $this->_user, $this->_pass, $this->_db)
or die(mysqli_error($this->_conn));
}
public function query($query) {
return mysqli_query($this->_conn, $query);
}
public function affectedRows() {
return mysqli_affected_rows($this->_conn);
}
class TheClassWhereYourMethodsYouHaveShownAre {
protected $_db;
public function __construct() {
$this->_db = new Database('host', 'user', 'pass', 'db');
}
public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) {
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
$this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
$this->_db->query($sql);
return $this->_db->affectedRows > 0;
}
mysql_query() sends a unique query
You can use mysqli_multi_query function but with PHP mysqli extension.
but, if you are dead set to use mysql_query then try this-
<?php
$str="query1;query2;"; //
$query = explode(';',$str);
// Run the queries
foreach($query as $index => $sql)
{
$result = mysql_query($sql);
// Perform an additional operations here
}
?>

Categories