PHP MySQL Warning: Illegal string offset 'title' - php

I get this error:
Warning: Illegal string offset 'title' in C:\wamp64\www\Beep\php\config.php on line 33
When using this function:
function getComments() {
global $pdo;
$sql = "SELECT * FROM `comments`";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetch();
$comments = array();
foreach ($results as $result) {
array_push($comments, new Comment($result["title"], $result["content"], $result["author"]));
}
return $comments;}
class Comment {
var $title;
var $content;
var $author;
/**
* Comment constructor.
* #param $title
* #param $content
* #param $author
*/
public function __construct($title, $content, $author){
$this->title = $title;
$this->content = $content;
$this->author = $author;
}
}
Line 33 is
array_push($comments, new Comment($result["title"], $result["content"], $result["author"]));

fetch() returns a single record. When you foreach() over the result, you iterator the values of the row, not rows.
Use fetchAll() to get all records.
$results = $stmt->fetchAll();
foreach ($results as $result) {
echo $result['title'];
}
In your initial code :
$results = $stmt->fetch();
foreach ($results as $result) {
echo $result; // here $result is id, then title, and so on.
}

Related

Getting uncaught refrence error in model.php file

I want to run a PHP website on localhost. I set up the server and imported the database but getting the following error...I Downloaded the website from the client c_panel public HTML folder and exported the database. I have to do changes in front-end and I have no idea of PHP(I am a Node.js developer, so if you can reference it with that to help me.). I just want to start the website locally, so that I can do the front-end changes. I'm getting the following error in my app/Models.php
Fatal error: Uncaught Error: Non-static method SB\Response::redirect() cannot be called statically in /Applications/MAMP/htdocs/app/src/sb/Model.php:475 Stack trace: #0 /Applications/MAMP/htdocs/app/src/sb/Model.php(12): SB\Model->db_error(Object(PDOException)) #1 /Applications/MAMP/htdocs/app/src/sb/DB.php(21): SB\Model->__construct() #2 /Applications/MAMP/htdocs/app/src/sb/DB.php(28): SB\DB->__construct() #3 /Applications/MAMP/htdocs/route/web.php(20): SB\DB::table('blogs') #4 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(66): require('/Applications/M...') #5 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(56): composerRequire6b60b5a5888bbd230d022934044bba82('8dab41e234cc925...', '/Applications/M...') #6 /Applications/MAMP/htdocs/vendor/autoload.php(7): ComposerAutoloaderInit6b60b5a5888bbd230d022934044bba82::getLoader() #7 /Applications/MAMP/htdocs/index.php(10): require_once('/Applications/M...') #8 {main} thrown in /Applications/MAMP/htdocs/app/src/sb/Model.php on line 475
Modal.php file:
<?php
namespace SB;
use PDO;
use PDOException;
class Model {
private $pdo = null;
public function __construct() {
try {
$this->pdo = new PDO(DSN, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
} catch (PDOException $e) {
$this->db_error($e);
}
}
/**
* Create table
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
function create_table($table, $data) {
$sql = "CREATE TABLE IF NOT EXISTS $table (";
$num = count($data);
$sql .= "`_id` bigint(20) PRIMARY KEY NOT NULL AUTO_INCREMENT, ";
for ($i = 0; $i < $num; $i++):
$sql .= $data[$i] . ", ";
endfor;
$sql .= "`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
$sql .="`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);";
$this->pdo->exec($sql);
return '<big>This code was executed. Please check manually if no table is created for the database<big> <br> '.$sql ;
}
/**
* insert
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function add($table, $data) {
ksort($data);
$this->pdo->beginTransaction();
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$s = $sth->execute();
$this->pdo->commit();
return $s;
}
/**
* insert with get auto increment _id
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function addGetId($table, $data) {
ksort($data);
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$res = $sth->execute();
if($res) {
return $this->pdo->lastInsertId();
} else {
return $res;
}
}
/**
* update
* #param string $table A name of table to insert into
* #param string $data An associative array
* #param string $where the WHERE query part
*/
public function modify($table, $data,$where,$where_data = []) {
ksort($data);
$fieldDetails = NULL;
foreach ($data as $key => $value) {
$fieldDetails .= "`$key`=:$key,";
}
$fieldDetails = rtrim($fieldDetails, ',');
$sth = $this->pdo->prepare("UPDATE `$table` SET $fieldDetails $where");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$val = rtrim($val," ");
$sth->bindValue(":$key", $val);
}
foreach ($where_data as $key => $value) {
$sth->bindValue(":".$key, $value);
}
return $sth->execute();
}
/**
* Fetch all
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_all($table,$cols = '*',$where = false, $type = null,$where_data = []) {
$statement = '';
if(!$where) {
$statement = "SELECT $cols FROM $table";
} else {
$statement = "SELECT $cols FROM $table $where";
}
$pre = $this->pdo->prepare($statement);
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM') {
return $pre->fetchAll(PDO::FETCH_NUM);
}
else if($type == 1 || $type == 'ASSOC') {
return $pre->fetchAll(PDO::FETCH_ASSOC);
} else {
return $pre->fetchAll(PDO::FETCH_OBJ);
}
}
/**
* Fetch one
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_one($table,$cols = '*',$where = false, $type = null,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM')
return $pre->fetch(PDO::FETCH_NUM);
else if($type == 1 || $type == 'ASSOC' )
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_some($table, $cols, $where, $operator) {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' :'. $key.', ' ;
}else{
$fields .= $key.' '.$operator.' :'. $key;
} $i++;
endforeach;
$pre = $this->pdo->prepare("SELECT $cols FROM $table WHERE $fields");
foreach ($where as $key => $value):
$pre->bindValue(":$key", $value);
endforeach;
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
/**
* Fetch row
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_row($table, $cols = '*', $where = false, $operator = '=') {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}else{
if(!is_array($where)){
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
} else {
return $this->pdo->fetch_some($table, $cols, $where, $operator);
}
}
}
/**
* Fetch rows
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_rows($table, $cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
public function fetch_one_assoc($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
public function fetch_one_object($table,$cols = '*',$where = false,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
if(!empty($where_data))
$pre->execute($where_data);
else
$pre->execute();
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_all_assoc($table,$cols = '*',$where = false) {
if(!$where) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch_all_object($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
e = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
/**
* Fetch type
* #param string $table A name of table to get all data
* #param string $where the WHERE query part
*/
public function fetch_type($table, $type = PDO::FETCH_OBJ, $limit = false,$cols = '*',$where = 1) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
if(!$limit){
return $pre->fetchAll($type);
}else{
return $pre->fetch($type);
}
}
public function fetch_sql($sql,$type = PDO::FETCH_OBJ) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
return $pre->fetchAll($type);
}
public function delete_row($table,$where,$operator = '=') {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' ? AND ' ;
} else {
$fields .= $key.' '.$operator.' ?';
} $i++;
endforeach;
$pre = $this->pdo->prepare("DELETE FROM $table WHERE $fields");
foreach ($where as $key => $value):
$a[] = $value;
endforeach;
return $pre->execute($a);
}
protected function deleteData($table,$where,$where_data=[]) {
$pre = $this->pdo->prepare("DELETE FROM $table $where");
foreach ($where_data as $key => $value) {
$pre->bindValue(":".$key, $value);
}
return $pre->execute();
}
public function customeDate($date=false) {
$date=date_create("$date");
return date_format($date,"dS-M-Y");
}
public function get_json($table) {
$rows = $this->pdo->fetch_all_assoc($table);
$out = "";
foreach($rows as $row) {
$cols = array_keys($row);
if ($out != "") {
$out .= ",";
}
foreach($cols as $i=>$col){
if($i==0){
$out .= '{"'.$col.'":"' . $row[$col] . '",';
} else {
$out .= '"'.$col.'":"' . $row[$col] . '",';
}
if($i==count($cols)-1) {
$out .= '"'.$col.'":"'. $row[$col] . '"}';
}
}
}
$out ='{"records":['.$out.']}';
return $out;
}
protected function connection_close() {
$this->pdo = null;
}
private function db_error($e) {
if(IS_DEBUGG):
die('
<br><h2><br>
<center>!Config Error.<br>
<small style="color:gray">Setup your .env file. Read Following Error</small>
</center></h2>
<h3>.env file variables</h3>
<ul>
<li>DB_HOST="Enter database host name"</li>
<li>DB_USER="Enter here database user name"</li>
<li>DB_PASS="enter Database Password"</li>
<li>DB_NAME="enter Database Name"</li>
<li>DB_DRIVER="DB DIRVER like `mysql`"</li>
</ul>
<br><div style="padding:50px;"><small style="color:lightgray"><pre>' . $e . '</pre></small></div>'
);
else:
return Response::redirect('404');
endif;
}
public function fetch_qry($sql,$one=0) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
if($one)
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
}
Update this line of code
public static function redirect($endpoint){
#header('Location:'.URL.$endpoint);
}
Or, you can create an instance of this class.
$response = new Response();
Then call this method.
$response->redirect('404');

Receive only first line when using mysql SELECT

/**
* #param string $nick
* #return array|null
*/
public function getPlayerByNick(string $nick) : ?array{
$query = "SELECT * FROM reports";
$result = $this->connection->query($query);
if($result instanceof \mysqli_result){
$data = $result->fetch_assoc();
$result->free();
var_dump($data);
}
return null;
}
When I do var_dump I get only first user in the table, but I want to get them all. How can I do that?
Hopefully this your help
/**
* #param string $nick
* #return array|null
*/
public function getPlayerByNick(string $nick) : ?array{
$query = "SELECT * FROM reports";
$result = $this->connection->query($query);
if($result instanceof \mysqli_result){
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["nick"]);
}
}
return null;
}
/**
* #param string $nick
* #return array|null
*/
public function getPlayerByNick(string $nick) : ?array{
$query = "SELECT * FROM reports";
$result = $this->connection->query($query);
if($result instanceof \mysqli_result){
while($data = $result->fetch_assoc()){
var_dump($data);
}
$result->free();
}
return null;
}

Passing array through bind_param

I'm passing an array of values through a bind_param function, the way I do this is like this:
<?php
class Query{
private $_mysqli;
/*
* #param object $mysqli
*/
public function __construct($mysqli)
{
$this->_mysqli = $mysqli;
}
/*
* #param string query
* #param string $types
* #param array $values
*/
public function read($query = "", $type = "", $params = array())
{
$query = ($query === "") ? die("Read error: Query") : $query;
$type = ($type === "") ? die("Read error: Type") : array($type);
$params = (count($params) == 0) ? die("Read error: Params") : $params;
$values = array();
foreach($params as $key => $value) {
$values[$key] = &$params[$key];
}
if ($stmt = $this->_mysqli->prepare($query))
{
call_user_func_array(array($stmt, "bind_param"), array_merge($type, $values));
$stmt->execute();
$fields = array();
for($i=0; $i<count($params); $i++){
$fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);
$array = array();
while($data = $stmt->fetch())
{
$array[] = $data;
}
return $array;
}
}
}
This is the way I use my function
<?php
//$mysqli is the mysqli connection
$query = new Query($mysqli);
$query_str = "SELECT * FROM users WHERE voornaam = ? AND achternaam = ?";
$types = "ss";
$params = array("Firstname", "Lastname");
var_dump($query->read($query_str, $types, $params));
?>
The part where I get stucked is:
<?php
$fields = array();
for($i=0; $i<count($params); $i++){
$fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);
$array = array();
while($data = $stmt->fetch())
{
$array[] = $data;
}
?>
Im not sure where it goes wrong, I have a feeling at the while loop.
hope you guys can help me making this function working :)
you are binding results , so you don't need to assign your fetched data to new variable,
mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables
to a prepared statement for result storage
while you are using call_user_func_array , and according to this comment, your loop :
while($data = $stmt->fetch())
{
$array[] = $data;
}
may be as follows:
while($stmt->fetch())
{
// params which you had bind it into bindParams
$array[] = $params;
}

when i run my program it keeps throwing these errors

Warning: Missing argument 1 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 2 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 3 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 4 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Notice: Undefined variable: host in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: username in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: password in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: db in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
This is my MysqlDB.php code
<?php
class MysqlDB {
protected $_mysql;
protected $_where = array();
protected $_query;
protected $_paramTypeList;
public function __construct ($host, $username, $password, $db) {
$this->_mysql = new mysqli($host, $username, $password, $db)
or die('There was a problem connecting to the database');
}
public function query($query)
{
$this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery();
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
* A convenient SELECT * function.
*
* #param string $tableName The name of the database table to work with.
* #param int $numRows The number of rows total to return.
* #return array Contains the returned rows from the select query.
*/
public function get($tableName, $numRows = NULL)
{
$this->_query = "SELECT * FROM $tableName";
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
*
* #param <string $tableName The name of the table.
* #param array $insertData Data containing information for inserting into the DB.
* #return boolean Boolean indicating whether the insert query was completed succesfully.
*/
public function insert($tableName, $insertData)
{
$this->_query = "INSERT into $tableName";
$stmt = $this->_buildQuery(NULL, $insertData);
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function update($tableName, $tableData)
{
$this->_query = "UPDATE $tableName SET ";
$stmt = $this->_buildQuery(NULL, $tableData);
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function delete($tableName) {
$this->_query = "DELETE FROM $tableName";
$stmt = $this->_buildQuery();
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function where($whereProp, $whereValue)
{
$this->_where[$whereProp] = $whereValue;
}
protected function _determineType($item)
{
switch (gettype($item)) {
case 'string':
return 's';
break;
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
}
protected function _buildQuery($numRows = NULL, $tableData = false)
{
$hasTableData = null;
if (gettype($tableData) === 'array') {
$hasTableData = true;
}
// Did the user call the "where" method?
if (!empty($this->_where)) {
$keys = array_keys($this->_where);
$where_prop = $keys[0];
$where_value = $this->_where[$where_prop];
// if update data was passed, filter through
// and create the SQL query, accordingly.
if ($hasTableData) {
$i = 1;
$pos = strpos($this->_query, 'UPDATE');
if ( $pos !== false) {
foreach ($tableData as $prop => $value) {
// determines what data type the item is, for binding purposes.
$this->_paramTypeList .= $this->_determineType($value);
// prepares the reset of the SQL query.
if ($i === count($tableData)) {
$this->_query .= $prop . " = ? WHERE " . $where_prop . "= " . $where_value;
} else {
$this->_query .= $prop . ' = ?, ';
}
$i++;
}
}
} else {
$this->_paramTypeList = $this->_determineType($where_value);
$this->_query .= " WHERE " . $where_prop . "= ?";
}
}
if ($hasTableData) {
$pos = strpos($this->_query, 'INSERT');
if ($pos !== false) {
$keys = array_keys($tableData);
$values = array_values($tableData);
$num = count($keys);
foreach ($values as $key => $val) {
$values[$key] = "'{$val}'";
$this->_paramTypeList .= $this->_determineType($val);
}
$this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES(';
while ($num !== 0) {
($num !== 1) ? $this->_query .= '?, ' : $this->_query .= '?)';
$num--;
}
}
}
if (isset($numRows)) {
$this->_query .= " LIMIT " . (int) $numRows;
}
$stmt = $this->_prepareQuery();
if ($hasTableData) {
$args = array();
$args[] = $this->_paramTypeList;
foreach ($tableData as $prop => $val) {
$args[] = &$tableData[$prop];
}
call_user_func_array(array($stmt, 'bind_param'), $args);
} else {
if ($this->_where)
$stmt->bind_param($this->_paramTypeList, $where_value);
}
return $stmt;
}
protected function _dynamicBindResults($stmt)
{
$parameters = array();
$results = array();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
$x = array();
foreach ($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
}
protected function _prepareQuery()
{
if (!$stmt = $this->_mysql->prepare($this->_query)) {
trigger_error("Problem preparing query", E_USER_ERROR);
}
return $stmt;
}
public function __destruct()
{
$this->_mysql->close();
}
}
?>
and i'm calling a function insert() through index.php
<?php
ob_start();
session_start();
require_once("phpinclude/include/membersite_config.php");
require_once("phpinclude/include/MySqlDB.php");
$DB = new MysqlDB('172.90.13.97','king','mi*****hhh','kxxxx_database');
if (isset($_GET['action'])){$action = htmlentities($_GET['action']);}
else{$action = NULL;}
$mysqldb = new MysqlDB();
?>
<?php if($action=='add_cart'){?>
<?php $data=array($arrival, $departure, $result, $roomID, $category_price); $table='tb_cart';?>
<?php $this->mysqldb->insert($table, $data); ?>
<?php }?>
Problem is in this line
$mysqldb = new MysqlDB();
The constructor requries arguments which are not passed. You need to pass $host, $username, $password, $db to constructor.
Your code acutally makes no sense. You could use $DB instead of creating new object. You also use $this->mysqldb in no object context. There are plenty of errors in your code.
To fix:
Remove this line $mysqldb = new MysqlDB();
Change <?php $this->mysqldb->insert($table, $data); ?> to $DB->insert($table, $data);
Script should +- look like:
<?php
ob_start();
session_start();
require_once("phpinclude/include/membersite_config.php");
require_once("phpinclude/include/MySqlDB.php");
$DB = new MysqlDB('172.90.13.97','king','mi*****hhh','kxxxx_database');
$action = !empty($_GET['action']) ? htmlentities($_GET['action']) : null;
if ($action == 'add_cart') {
$data = array(
'arrival' => $arrival,
'departure' => $departure,
'result' => $result,
'roomID' => $roomID,
'category_price' => $category_price
);
$DB->insert('tb_cart', $data);
}

Pass values from array to a function

I have the following code which gets all news:
private function get_news()
{
$news = array();
$query = $this->database->query("SELECT * FROM `news` ORDER BY `news_id` DESC");
while($row = mysql_fetch_array($query))
{
$news[] = $row;
}
return $news;
}
In the same class I have a bbedit() function. I want to get the value of $news[int]['news_content'] and pass it to that function bbedit().
Use $this to call a function within class:
private function bbedit(){
$news = $this->get_news(); // news will have all your array
foreach($news as $key => $val){
// do something with $val['news_content'];
}
}
or
while($row = mysql_fetch_array($query)){
$news[] = $this->bbedit($row['news_content']);
}

Categories