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);
}
?>
I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'";
// for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true®='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to convert this simple php code to codeigniter model and controller .
inside while loop when fetching data $row indexing should be comes through foreach loop($columns).
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dt";
$columns[0] = 'id';
$columns[1] = 'first_name';
$columns[2] = 'last_name';
$columns[3] = 'position';
$columns[4] = 'office';
$columns[5] = 'salary';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$where_clause = "";
$where_clause_array = [];
foreach($_REQUEST['columns'] as $key=>$column) {
if($column['search']['value'] != '') {
$where_clause_array[] = $columns[$column['data']]." LIKE "."'".$column['search']['value']."%'";
}
}
if(sizeof($where_clause_array) > 0) {
$where_clause = " WHERE ".implode(" AND ", $where_clause_array);
}
$order_by = " ORDER BY ".$columns[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir'];
$limit = " LIMIT ".$_REQUEST['start'].", ".$_REQUEST['length'];
$sql = "SELECT * FROM users".$where_clause.$order_by.$limit;
$result = $conn->query($sql);
$sqlTotal = $sql = "SELECT * FROM users".$where_clause.$order_by;
$resultTotal = $conn->query($sqlTotal);
$finalResult = [];
$finalResult['draw'] = $_REQUEST['draw'];
$finalResult['recordsTotal'] = $resultTotal->num_rows;
$finalResult['recordsFiltered'] = $resultTotal->num_rows;
$i=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$finalResult['data'][$i][] = $row["id"];
$finalResult['data'][$i][] = $row["first_name"];
$finalResult['data'][$i][] = $row["last_name"];
$finalResult['data'][$i][] = $row["position"];
$finalResult['data'][$i][] = $row["office"];
$finalResult['data'][$i][] = $row["salary"];
$i++;
}
} else {
$finalResult['data'] = [];
}
echo json_encode($finalResult);
$conn->close();?>
I need to convert this simple php code to codeigniter model and controller .
inside while loop when fetching data $row indexing should be comes through foreach loop($columns).
Thanks
Step-1
First thing first, DB credentials goes to application->config->database.php
Step-2
Controller
class controllerName extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('your_model');
}
public function index(){
$data['columns'][0]='id';
$data['columns'][1]='first_name';
$data['columns'][2]='last_name';
$data['columns'][3]='position';
$data['columns'][4]='salary';
$result=json_encode($this->your_model->getResults($data));
print_r($result);
}
}
Step-3
Model
class Your_model extends CI_Model {
public function getResults($data)
{
$where_clause = "";
$where_clause_array = [];
foreach($_REQUEST['columns'] as $key=>$column) {
if($column['search']['value'] != '') {
$where_clause_array[] = $columns[$column['data']]." LIKE "."'".$column['search']['value']."%'";
}
}
if(sizeof($where_clause_array) > 0) {
$where_clause = " WHERE ".implode(" AND ", $where_clause_array);
}
$order_by = " ORDER BY ".$columns[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir'];
$limit = " LIMIT ".$_REQUEST['start'].", ".$_REQUEST['length'];
}
$result=$this->db->query('SELECT * from users'$where_clause.$order_by.$limit)->result_array();
return $result;
}
I have a function in PHP and I would like to export an array from my MYSQL Database and then use the rows in a loop to do some stuff with them.
$DB_Server = "XXX.XXX.XXX.XXX";
$DB_Username = "XXXX";
$DB_Password = "XXXXX";
$DB_Database = "XXXXX";
$conn = new mysqli($DB_Server, $DB_Username, $DB_Password, $DB_Database);
$query = "Select Name, Wert from test.DBPBX";
function show(array $options) {
global $showresult, $master, $conn, $query;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$cnlongname = $row["Name"];
$usercontent = $row["Wert"];
$cn = $cnlongname;
$options['config']->value = 1;
$config = $options["config"]->value;
$show = new SimpleXMLElement("<show/>");
$user = $show->addChild("user");
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
$showresult = $master->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
$mod = "text=".$usercontent;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
// do it
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
}
For $cn I would like to use $cnlongname (or $row["Name"]). And for $mod I would like to use $usercontent (or $row["Wert"]). However when I would like to use it I get an error after the first loop:
Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, string given in /sample.php on
line 175
Line 175 is:
while ($row = mysqli_fetch_assoc($result)) {
Can you please help me?
Inside your while loop you overwrite your result, therefore you lose your mysql result and cannot query it any more.
// do it
$result = $master->Admin($cmd);
Use a different variable there. :)
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;
}