Issues in printing out php array - php

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

Related

Android Paginate JSON Data from PHP Mysql to App

The below PHP code gets all data from a MySQL DB and sends it to an android app. I want the data to be paginated.
ALL DATA PHP CODE
<?php
include 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$HostName;dbname=$DatabaseName", $HostUser, $HostPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `tiffa`");
$stmt->execute();
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($data);
} catch (PDOException $e) {
print "Connection failed! Please Try Again Or Contact Us: " . $e->getMessage() . "<br/>";
die();
$conn = null;
}
POJO/DATA MODEL CLASS
public class ImageList {
#SerializedName("image1name")
private String name;
#SerializedName("county")
private String county;
#SerializedName("image1URL")
private String imageurl;
#SerializedName("image2URL")
private String image2url;
public ImageList(String name,String county,String imageurl, String image2url) {
this.name = name;
this.county = county;
this.imageurl = imageurl;
this.image2url = image2url;
}
public String getName() {
return name;
}
String getCounty() {
return county;
}
String getImageurl() {
return imageurl;
}
String getImage2url() {
return image2url;
}
}
I have tried to pass the page_number and item_count (which come from the app) but I can't seem to get it. Here is my tried PHP Code. The POJO remains the same.
<?php
$page_number = $_GET['page_number'];
$item_count = $_GET['item_count'];
$from = $page_number * $item_count - ($item_count - 1);
$to = $page_number * $item_count;
$data = array();
include 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$HostName;dbname=$DatabaseName", $HostUser, $HostPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `tiffa`");
$stmt->execute();
if ($to > $stmt) {
array_push($response, array('status' => 'end'));
echo json_encode($response);
} else {
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($data);
}
array_push($response, array('images' => $images));
sleep(2);
echo json_encode($response);
catch (PDOException $e) {
print "Connection failed! Please Try Again Or Contact Us: " . $e->getMessage() . "<br/>";
die();
$conn = null;
}
Thanks for the leads #Nigel Ren. I resolved this by
<?php
$page_number = $_GET['page_no'];
$item_count = $_GET['item_cnt'];
$from = $page_number*$item_count - ($item_count-1);
$to = $page_number*$item_count;
$response=array();
$stats=array();
include 'dbconfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$total = mysqli_num_rows(mysqli_query($conn, "SELECT id from db1"));
if($to>$total)
{
array_push($response,array('status'=>'end'));
echo json_encode($response);
}
else
{
array_push($response,array('status'=>'ok'));
$count = $from;
$images = array();
$start = ($page - 1) * $limit;
//SQL query to fetch data of a range
$sql = "SELECT * from db1 limit $start, $item_count";
//Getting result
$result = mysqli_query($conn,$sql);
//Adding results to an array
$res = array();
while($row = mysqli_fetch_array($result))
{
$image122 = $row['image122'];
$image_path = $image122;
array_push($images,array('id'=>$count,'image_path'=>$image_path));
$count = $count+1;
}
array_push($response,array('images'=>$images));
sleep(2);
echo json_encode($response);
}
?>

OOP PHP - proper way to pass $_POST values from form to database_write function

I have trouble understanding OOP...
Lets say I wanted to create a page that adds a new user to a database and wanted to work with classes.
For that scenario i'd create a form with a function.
There are forms for each CRUD functionality - renderHTMLFormAddUser() :
...
<form action="" method="POST" >;
<label>Shopname*</label><br>;
<input type="text" name="shopname" class="input_wide" required><br>;
<label>Username*</label><br>;
<input type="text" name="username" class="input_wide" required><br>;
<input type="submit" value="add" name="submit" >
...
a DataBaseConnector class:
class DataBaseConnector
{
protected $con;
public function __construct()
{
$this->con=mysqli_connect('mariaDB','root','123456','produktmuster');
}
public function getConnection()
{
return $this->con;
}
public function __destruct()
{
$this->con->close();
}
}
and a QueryDatabase class that requires the DataBaseConnector connection as a transfer parameter in its constructor:
class QueryDatabase
{
private $con;
public function __construct(DataBaseConnector $con)
{
$this->con = $con;
}
public function addUser($shopname,$username)
{
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
$result = mysqli_query($this->con->connect(), $sql);
return $result;
}
To get the $_POST values in the QueryDatabase add User function, i'd need to declare variables like so:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
But is there a better way to do so?
Like maybe renderHTMLFormAddUser()->'shopname'.
Im just trying to understand what is the cleanest way to code in this scenario.
Because using a function to render the forms the adduser.php would look something like this:
$createuserform=new Forms();
$createuserform->renderHTMLFormAddUser();
$shopname= $_POST['shopname']; // this is what confuses me, you'd have to look into the
$username= $_POST['username']; // renderHTMLFormAddUser() function to see the code
$db = new DataBaseConnector();
$query= new QueryDatabase();
$query->addUser($shopname,$username)
Should I just create an own page that posts the form to a page that then uses the data?
In the beginning i simply used no transfer parameters with the addUser function, and it started with declaring the $_POSTs:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
...
But I was told it was unsafe to do so - in that regard, I sanitize my data but for the sake of easier example i stripped away all the unnecessary code.
Should I take a completely different approach, just would like to know the cleanest way to add form input data into a database.
Well, there are many approaches to do this. You can also do my OOPs approach:
Make a define.php to set the constant variables & database connection variables:
define.php
define("DB_HOSTNAME", "localhost");
define("DB_USERNAME", "your_username");
define("DB_PASSWORD", "your_password");
define("DB_NAME", "your_databasename");
define("custom_variable", "custom_variable_value");
define("baseurl", "https://localhost/myproject/");
Then, make dbase.php, to create a dynamic SQL function:
You don't need to change this file. You just need to call this class. This file work as the core file of the system.
Dbase.php
<?php session_start();
date_default_timezone_set("Asia/Karachi");
require_once("define.php");
Class Dbase
{
private $Host = DB_HOSTNAME;
private $UserName = DB_USERNAME;
private $Password = DB_PASSWORD;
private $DBname = DB_NAME;
private $connDb = false;
public $LastQuery = null;
public $AffectedRows = 0;
public $InsertKey = array();
public $InsertValues = array();
public $UpdateSets = array();
public $id;
public function __construct()
{
$this->connect();
}
protected function connect()
{
$this->connDb = #mysqli_connect($this->Host, $this->UserName, $this->Password);
if (!($this->connDb)) {
die('Database Connection Failed.<br>' . mysql_error($this->connDb));
} else {
$Select = mysqli_select_db($this->connDb,$this->DBname);
if (!$Select) {
die('Database Selection Failed.<br>' . mysql_error($this->connDb));
}
}
mysqli_set_charset($this->connDb,'utf8');
}
public function close()
{
if (!mysqli_close($this->connDb)) {
die('Closing Connection Failed.<br>');
}
}
public function escape($value)
{
if (function_exists('mysql_real_escape_string')) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else {
if (!get_magic_quotes_gpc()) {
$value = addcslashes($value);
}
}
return $value;
}
public function query($sql)
{
$query = $sql;
$result = mysqli_query($this->connDb,$sql);
// $this->displayQuery($result);
return $result;
}
public function displayQuery($result)
{
if (!$result) {
$output = 'Database Query Failed' . mysql_error($this->connDb) . '<br>';
$output .= 'Last Query was' . $this->LastQuery;
die($output);
} else {
$this->AffectedRows = mysqli_affected_rows($this->connDb);
}
}
public function fetchAll($sql)
{
$result = $this->query($sql);
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
// mysql_free_result($result);
return $output;
}
public function fetchOne($sql)
{
$output = $this->fetchAll($sql);
return $output;
// return array_shift($output);
}
public function prepareInsert($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->InsertKey[] = $key;
$this->InsertValues[] = $this->escape($value);
}
}
}
public function insert($table = null)
{
if (!empty($table) && !empty($this->InsertKey) && !empty($this->InsertValues)) {
$sql = "insert into '{$table}' ('";
$sql .= implode("','", $this->InsertKey);
$sql .= "') values ('";
$sql .= implode("','", $this->InsertValues);
$sql .= "')";
if ($this->query($sql)) {
$this->id = $this->lastId();
return true;
}
return false;
} else {
return false;
}
}
public function prepareUpdate($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->UpdateSets[] = "`{$key}` = '" . $this->escape($value) . "'";
}
}
}
public function update($table = null, $id = null, $whereId)
{
if (!empty($table) && !empty($id) && !empty($this->UpdateSets)) {
$sql = "update `{$table}` set";
$sql .= implode(",", $this->UpdateSets);
// $sql.="where id='".$this->escape($id)."'";
$sql .= "where '" . $whereId . "'='" . $this->escape($id) . "'";
return $this->query($sql);
} else {
return false;
}
}
public function lastId()
{
return mysqli_insert_id($this->connDb);
}
public function TotalNumberOfRecords($sql)
{
$result = $this->query($sql);
$output = mysqli_num_rows($result);
return $output;
}
public function GetServerInfo()
{
return mysqli_get_server_info();
}
}
Create a Query.php file. This file work as your model file as in MVC.
Query.php
<?php include "Dbase.php";
Class Query extends Dbase
{
public function __construct()
{
$this->connect();
date_default_timezone_set("Asia/Karachi");
}
public function getData($idlevelOne)
{
$sql = "SELECT * FROM `table` where level_one_id=$idlevelOne ORDER BY `sorting` ASC";
$result = $this->fetchAll($sql);
return $result;
}
/*For Insert & Edit, use this fucntion*/
public function editMember($email, $phone, $address, $city, $country, $zipcode, $id)
{
$sql = "UPDATE `members` SET `email` = '" . $email . "', `phone` = '" . $phone . "', `address` = '" . $address . "'
, `city` = '" . $city . "', `country` = '" . $country . "', `zip_code` = '" . $zipcode . "'
WHERE `id` = '$id'";
$result = $this->query($sql);
return $result;
}
}
Now, you just need to call the Query class in your PHP files to get the data.
<?php
include "Query.php";
$ObjQuery = new Query();
$ObjQuery->getData(1);

How can I get my data with a query in order to create an edit function with a class in regards to OOP?

Pleassee help. I'm at a loss!! I am creating a blog site where the admin can edit and delete their post. However, when I pass my query:
Fatal error: Uncaught Error: Call to a member function query()
on null in C:\xampp\htdocs\tp02\TP2PHP\Posting.class.php:22
Stack trace:
'#0' C:\xampp\htdocs\tp02\TP2PHP\editardelete.php(15):
Posting->getData('SELECT * FROM b...')
'#1' {main} thrown in
C:\xampp\htdocs\tp02\TP2PHP\Posting.class.php on line 22
Plus a few undefine indexes.
Notice: Undefined index: titulo in C:\xampp\htdocs\tp02\TP2PHP\editardelete.php on line 10
Notice: Undefined index: contenido in C:\xampp\htdocs\tp02\TP2PHP\editardelete.php on line 11
Notice: Undefined property: Posting::$conn in C:\xampp\htdocs\tp02\TP2PHP\Posting.class.php on line 22
My guess is my connection. Please help Thank you
Posting.class.php
<?php
require_once 'conexion.php';
require_once 'BaseDato.class.php';
require_once 'Admin.class.php';
class Posting extends Connectdb {
public $titulo;
public $contenido;
public function __construct($titulo,$contenido) {
$this->titulo = $titulo;
$this->contenido = $contenido;
}
public function getData($query) {
$result = $this->conn->query($query);
if ($result == false) {
return false;
}
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function execute($query) {
$result = $this->conn->query($query);
if ($result == false) {
echo 'Error: cannot execute the command';
return false;
} else {
return true;
}
}
public function delete($id, $table) {
$query = "DELETE FROM blogtp_1 WHERE id = $id";
$result = $this->conn->query($query);
if ($result == false) {
echo 'Error: cannot delete id ' . $id . ' from table ' . $table;
return false;
} else {
return true;
}
}
/*public function escape_string($value)
{
return $this->conn->real_escape_string($value);
} */
}
?>
AND here is the other page xcalled editardelete.php :
<?php
// including the database connection file
require_once 'conexion.php';
include 'BaseDato.class.php';
include 'Posting.class.php';
//datos de la conexion
$conexion = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
session_start();
$titulo = $_POST['titulo'];
$contenido = $_POST['contenido'];
$posting = new Posting($titulo,$contenido);
//fetching data in descending order (lastest entry first)
$query = "SELECT * FROM blogtp_1 ORDER BY id DESC";
$result = $posting->getData($query);
//echo '<pre>'; print_r($result); exit;
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>titulo</td>
<td>contenido</td>
</tr>
<?php
foreach ($result as $key => $res) {
//while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['titulo_del_post']."</td>";
echo "<td>".$res['contenido_del_post']."</td>";
echo "<td>Editar </td>";
}
?>
</table>
</body>
</html>
This is my connection class:
<?php
class Connectdb{
private $host;
private $user;
private $pass;
private $db;
protected function connect(){
$this->host = "localhost";
$this->user = "root";
$this->pass = "";
$this->db = "blog";
$conn = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
return $conn;
}
}
?>
first we have to restructure your code.
Your connection class.
<?php
// error class just incase an error occured when trying to connect
class __errorClass
{
public function __call($meth, $args)
{
echo $meth . '() failed! Database connection error!';
}
}
class Connectdb{
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "blog";
public function connect()
{
$conn = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
if ($conn->errorCode == 0)
{
return $conn;
}
else
{
return new __errorClass();
}
}
}
?>
Next in you Posting Class.
<?php
require_once 'conexion.php';
require_once 'BaseDato.class.php';
require_once 'Admin.class.php';
class Posting{
public $titulo;
public $contenido;
private $conn;
public function __construct($titulo,$contenido) {
$this->titulo = $titulo;
$this->contenido = $contenido;
$db = new Connectdb();
$this->conn = $db->connect();
}
public function getData($query)
{
$result = $this->conn->query($query);
if ($result == false) {
return false;
}
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function execute($query)
{
$result = $this->conn->query($query);
if ($result == false) {
echo 'Error: cannot execute the command';
return false;
} else {
return true;
}
}
public function delete($id, $table)
{
$query = "DELETE FROM blogtp_1 WHERE id = $id";
$result = $this->conn->query($query);
if ($result == false) {
echo 'Error: cannot delete id ' . $id . ' from table ' . $table;
return false;
} else {
return true;
}
}
/*public function escape_string($value)
{
return $this->conn->real_escape_string($value);
} */
}
?>
Finally in your editardelete.php file.
<?php
// should keep session here!
session_start();
include 'BaseDato.class.php';
include 'Posting.class.php';
// for a quick check you can use this function
// would check for titulo in GET, POST and SESSION
function is_set($name)
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
elseif (isset($_GET[$name]))
{
return $_GET[$name];
}
elseif (isset($_SESSION[$name]))
{
return $_SESSION[$name];
}
else
{
return false;
}
}
// you have to check if titulo and contenido is set
// this would reduce error level to zero!
$result = [];
if ( is_set('titulo') && is_set('contenido'))
{
$titulo = is_set('titulo');
$contenido = is_set('contenido');
$posting = new Posting($titulo,$contenido);
//fetching data in descending order (lastest entry first)
$query = "SELECT * FROM blogtp_1 ORDER BY id DESC";
$result = $posting->getData($query);
//echo '<pre>'; print_r($result); exit;
}
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>titulo</td>
<td>contenido</td>
</tr>
<?php
if (count($result) > 0)
{
foreach ($result as $key => $res) {
echo "<tr>";
echo "<td>".$res['titulo_del_post']."</td>";
echo "<td>".$res['contenido_del_post']."</td>";
echo "<td>Editar </td>";
}
}
?>
</table>
</body>
</html>
I hope this helps. Happy coding vittoria!

Serach database not working in php pdo

Please i have been trying to make search in php pdo but is not working when i search it will only show the current title i searched for.
I have been using MYSQL but is showing error at the top of my page but is searching very well like i wanted it to be please can someone convert this Mysql to PDO for me or MYSQLI but i prefer PDO because i understand it more
here is my PHP to get search using mysql
<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
if(isset($_GET['q'])){
$button = mysql_real_escape_string($_GET ['t']);
$search = mysql_real_escape_string($_GET ['q']);
$construct = "";
if(!$search)
echo 'The Query String field is required.';
else{
if(strlen($search)<=1)
echo 'The Query String is too short.';
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_select_db("your database name");
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each){
$x =0; $x++;
if($x==1){$construct .="title LIKE '%$search_each%'";}
else {
$construct .="AND blog LIKE '%$search_each%' AND tags LIKE '%$search_each%'";
}
}
$construct ="SELECT * FROM blogtd WHERE $construct AND action = 'active'";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if($foundnum==0)
echo "Sorry, there are no matching result for";
else{
echo "We've found match";
while($runrows = mysql_fetch_assoc($run)){
$title = $runrows ['title'];
$body = mysql_real_escape_string($runrows ['blog']);
?>
<div>
<?php
echo $title."<br/>";
echo $body;
?></div>
<?php
}
}
}
}
}
?>
Here is my db-controller and i saved it in a different folder _inc/dbcontroller.php
<?php
class DBController {
//include('Define.php');
private $host = "localhost";
private $user = "root";
private $password = "12345";
private $database = "ServerDBsclab";
function __construct() {
$db_conn = $this->connectDB();
if(!empty($db_conn)) {
$this->selectDB($db_conn);
}
}
function connectDB() {
$db_conn = mysql_connect($this->host,$this->user,$this->password);
return $db_conn;
}
function selectDB($db_conn) {
mysql_select_db($this->database,$db_conn);
}
function runQuery($query) {
$result = mysql_query($query);
while($row=mysql_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysql_query($query);
$rowcount = mysql_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}
}
$db_conn = null;
?>
Here is my php pdo that i tried to use but is not working please help me with this so it will work like the above code
<?php
if(isset($_GET['postid'])){
echo '<h5 style="color: #2f2f2f;">Search</h5><br/>';
$matchpost = $blog_title;
$button = mysql_real_escape_string($_GET['postid']);
$q = $blog_title;
$search_output = "";
// Prepare statement
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$search = $db_conn->prepare("SELECT * FROM `blogtd` WHERE `blog` LIKE ?");
$search->execute(array("%$q%"));
foreach($search as $s){
$id = $s["BID"];
$title = $s["blog"];
$body = substr($s["body"], 0, 50);
$search_output .= '<article>
<header><a href="'.$id.'">
<h5>'.$title.'</h5>
</a></header>
<p>'.$body.'...</p></article>';
}
echo $search_output;
}
?>
Its wat everyone is saying. Keep everything by 1 extension. If u use PDO, do everything in PDO. If u use mysqli. Do everything in mysqli. Never use mysql. (we live in 2016 now).
I'm only looking at your PDO code. It seems your missing some code how do you want to get your mysql data. Your don't fetch anything. I created a similar script for you that works a little different. Including my PDO class. Test it in your own server and check it that is working.
_inc/dbcontroller.php
<?php
class DBController{
private $conn;
public $error;
private $stmt;
public function __construct(){
$driver = 'mysql';
$host = 'localhost';
$port = 3306;
$user = 'user';
$pass = 'pass';
$db = 'mydb';
$dsn = $driver.':host='.$host.';port='.$port.';dbname='.$db;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$this->conn = new PDO($dsn, $user, $pass, $options);
}
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function error(){
return $this->stmt->errorInfo();
}
public function errorInfo(){
return $this->stmt->errorInfo();
}
public function prepare($query){
$this->stmt = $this->conn->prepare($query);
}
public function bind($param, $value, $type = null){
if(is_null($type)){
switch(true){
case is_int($value): $type = PDO::PARAM_INT; break;
case is_bool($value): $type = PDO::PARAM_BOOL; break;
case is_null($value): $type = PDO::PARAM_NULL; break;
default: $type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function getOne(){
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
public function getAll(){
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
public function getAllObject(){
$result = new stdClass;
$count = 0;
while($row = $this->stmt->fetchObject()){
$count++;
$result->$count = $row;
}
return $result;
}
public function getLastInsertId(){
return $this->conn->lastInsertId();
}
public function free(){
$this->stmt = null;
}
}
Your call file
<?php
$search = filter_input(INPUT_GET, 'q');
$output;
if(!empty($search)){
require_once("_inc/dbcontroller.php");
$db_handle = new DBController();
$db_handle->prepare('SELECT * FROM blogtd WHERE blog LIKE :search');
$db_handle->bind(':search', '%'.$search.'%');
$db_handle->execute();
$output = $db_handle->getAll(); // This is the thing i'm missing in your script.
$db_handle->free();
}
if(!is_null($output)):
$html = '';
foreach($output as $i => $row){
$id = $row->BID;
$title = $row->blog;
$body = substr($row->body, 0, 50);
$html .= '
<article>
<header>
<h5>'.$title.'</h5>
</header>
<p>'.$body.'</p>
</article>';
}
echo $html;
else: ?>
<form id='searchform' method="GET" target="#">
<input type='text' name='q' value=''/>
<input type='submit' value='search'/>
</form><?php
endif;

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.

Categories