I've got a situation, where the object created in the top position in my PHP file, gets deconstructed before reaching the end of the PHP code on that file
File1.php:
//* This is all in the same PHP file *//
<?php
session_start();
include 'includes/user.inc.php';
$userOBJ = new User; //Declaring the object
?>
//*** jQuery and HTML code here ***//
<?php
if($userOBJ->isAdmin($_SESSION['session_u-name']) == true){
AdminControl();
}
// This code gets done without any problem
function AdminControl(){
echo "<a id='dbControlAdmin' onclick='changeDisplayAdm()'>Database
Control</a>";
}
?>
//*** More HTML and jQuery Code here ***//
<?php
$userOBJ->getUsersName(); //The object is no longer available when reaching this code
?>
In the Object Class I have this function as the deconstructor:
public function __destruct(){
echo "<b style='color: red;'>Status:</b> Database Connection->Disconnect";
}
This are the functions that are called through the Object:
public function isAdmin($user){
$userToGet = $user;
$stmt = $this->Connect()->prepare("SELECT admin_db FROM user_secure WHERE username_db=?");
$stmt->execute([$userToGet]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$value = $row["admin_db"];
if($value == 1){
return true;
} else {
return false;
}
}
}
public function getUsersName(){
$stmt = $this->Connect()->prepare("SELECT username_db FROM user_secure");
$stmt->execute();
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)){
echo "<option value='" . $row['username_db'] . "'>" . $row['username_db'] . "</option>";
}
}
}
When I run the website, in the top left corner appears this message
Status: Database Connection->Disconnect
Which is the instruction that the object has in the __destruct function, and the website deploys a PHP error where that last function call is: $userOBJ->getUsersName();
The error is:
Notice: Undefined index: username_db in C:\wamp64\www\NewKali\includes\user.inc.php on line 57
I don't get where the __destruct function is called or why it is called! Hope that you can help me.
Thank you for your time!
rename column username_db into a column, which actually exists on the server.
OWNER EDIT:
I changed $row['username_db'] to $row["username_db"] and it worked... (Also changed a few other things)
My final code in the function was this:
public function getUsersName(){
$stmt = $this->Connect()->prepare("SELECT * FROM user_secure");
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$value = $row["username_db"];
echo "<option value='" . $value . "'>" . $value . "</option>";
}
}
You're setting $userOBJ = new User twice.
Related
So these are my codes.
model
function read() {
$sql= "SELECT * from table WHERE name = 'rabin'";
$query = $this->db->query($sql);
$res = $query->result_array();
return $res;
}
controller
function show() {
$this->load->model("db");
$array['data'] = $this->db->read();
$this->load->view("page", $array);
}
view
foreach($data as $val) {
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
Here, when there are no records in the database satisfying the WHERE clause in the query, the model returns null and I get error saying $data expects parameter 1 to be array, null given. There are several methods to deal with this situation. But, what would be the best possible way to handle this situation ?
The problem is the foreach needs data provided by the database, but you didn't give them anyone.
So I will do this instead:
Model
function read() {
$this->db->where('name', 'rabin');
$res = $this->db->get('table');
return ($res->num_rows() > 0) ? $query->result_array() : false;
}
Controller
function show() {
// $this->(model_name)->(function);
$result = $this->db_model->read();
if ( $result ) {
// if there has data returns, load view
$array['data'] = $result;
$this->load->view('page', $array);
}
else {
// otherwise, show errors.
// you can handle by yourself
echo "no result!";
}
}
Use the Query Builder always to prevent from SQL Injection.
The Model returns the result_array, or false, so that you can handle the result.
Use $res->row_array() instead if your query result returns only one row. (like the certain one member).
You should rename your model from db to (example)db_model or other. The db will conflict with the system method.
The way to load function from model is $this->model_name->function_name for example, it should be $this->db_model->read().
You should load the model (if it is db_model) like $this->load->model('db_model') in public function __construct() { }.
In your model try out this
function read() {
$this->db->select()->from('table')->where('name', 'rabin');
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
and then to check you are getting the result - in your controller,
function show() {
$this->load->model("db");
$array= array( 'data' => $this->db->read());
$this->load->view("page", $array);
}
To view the result in your view file do print_r($data);
And then let me know what you get / result
In your view put if than else block with foreach loop in it. Smething like:
<?php if ($data != FALSE): ?>
<?php
foreach($data as $val)
{
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
?>
<?php else: ?>
<?php echo "There is no demanded data."; ?>
<?php endif; ?>
This is much like Benyi's answer with a little twist.
Probably you will eventually want the model to be able to look for names other than 'rabin'. So this shows how to accomplish that by passing a value to the model. Also, this model method always returns something useful to the controller.
function read($name)
{
$noRecords[] = array('name' => "No Results!", 'address' => "");
if(empty($name))
{
return $noRecords;
}
//Such a simple query does not require Query Builder which adds a
//lot of extra processing to get to the same place as this query statement
$sql = "SELECT * from table WHERE name = ?";
//This is a "bound" query that will escape the input to guard against injection attacks
$query = $this->db->query($sql, array($name));
$res = $query->result_array();
if($res->num_rows() > 0)
{
return $query->result_array();
}
else
{
// send the controller an array containing a little something to explain what happened
return $noRecords;
}
//the above if/else could also be expressed with this ternary
// return $res->num_rows() > 0 ? $query->result_array() : $noRecords;
}
The controller is now very light-weight.
function show()
{
$name = 'rabin'; //some data for the model
$array['data'] = $this->db_model->read($name);
$this->load->view('page', $array);
}
Your view is also greatly simplified
<?php foreach($data as $val): ?>
<p><?php echo $val['name']; ?>"</p>"
<p><?php echo $val['address']; ?>"</p>"
<?php endforeach; ?>
I'm calling a specific function, either getTaskList0, getTaskList1, or getTaskList2, each the same as below, with the number after task referring to the getTaskList number (in TaskManagerDAO):
function getTaskList0(){
$lst=array();
$con=$this->getDBConnection();
$result = $con->query("SELECT name, score FROM task0 ORDER BY score DESC");
$i = 0;
$counter=0;
while (($row =$result->fetch_row()) && ($counter<5)) {
$rec = new Task($row[0],$row[1]);
$lst[$i++]=$rec;
$counter++;
}
return $lst;
}
Task:
<?php
class Task{
public $name;
public $score;
function __construct($name,$score) {
$this->name = $name;
$this->score = $score;
}
}
The function is called in here:
<?php
session_start();
if(!class_exists('Action')){
include_once 'Action.php';
}
if(!class_exists('TaskManagerDAO')){
include_once 'TaskManagerDAO.php';
}
class Action_DisplayList implements Action{
public function execute($request){
if(!isset($_SESSION['functCount']))
$_SESSION['functCount']=0;
$functCount=$_SESSION['functCount'];
$functionName="getTaskList{$functCount}";
echo $functionName;
$dao = new TaskManagerDAO();
$names = $dao->$functionName();
$_SESSION['names'] = $names;
$last = sizeof($names);
$start = 0;
$_SESSION['start'] = $start;
$_SESSION['last'] =$last;
header("Location: tasklist.php");
}
}
?>
I'm trying to call the function by putting a variable at the end of the function name as a string and then calling the function. This works as I don't get any errors, but the list does not show up in the table, which is what this code is supposed to do:
<?php
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
include 'Action_Add.php';
Action_Add::execute();
}
$functCount=0;
$_SESSION['functCount']=0;
$names = $_SESSION['names'];
$start=$_SESSION['start'];
$last = $_SESSION['last'];
for($count = $start; $count < $last; $count++){
$name=$names[$count];
echo "<tr>";
echo "<td>".($count+1)."</td>";
echo "<td>".$name->name."</td>";
echo "<td>".$name->score."</td>";
echo "</tr>";
}
?>
EDIT:
I restarted my computer and everything and for the first run load of the page it worked perfectly. After that though, it stopped working though.
Use session_start(); before start using $_SESSION. So in your case, try something like
<?php
session_start();
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
//.... remaining code here
Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
I have a php script for check the availability of some data. I call this script from external jquery. the jquery is running fine. here is my php:
<?php
$avares = checkAva($fi_nm, $tbl_nm, $txtval);
echo $avares;
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "") or die("query failed");
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
}
?>
$curval is the variable coming from external jquery. my problem is that the while loop seems to run only once though there are lot of entries in the DB. I checked it with an integer variable and the while loop seems to run only once. can you help me to solve that?
Look at your code.
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
you have used return, if its true it returns and false then also returns change those according to your needs. The return statement immediately ends execution of the current function
It will by design as you have a return statement. From what you have said your not actually wanting it to return but to set a variable that at end of execution will return no or yes. I could be wrong on this but hey ho.
<?php
echo checkAva($fi_nm, $tbl_nm, $txtval);
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table) or die("query failed");
$noOrYes = "yes";
while ($a_row = mysql_fetch_array($avres)) {
if($curval == $a_row[$field]) {
$noOrYes = "no";
}
}
return $noOrYes;
}
?>
The possible issue that can cause Loop to iterate once are:
Error in the Variable used for the $query and $result
Same name Variable inside and outside of the Loop
Incorrect placement of Return statement
Invalid Mysql Statement
Directly put the condition in your Query like
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "
WHERE `".$field."` = '".$curVal."'");
$res = mysql_fetch_array($avres);
if(is_array($res) && count($res) > 0)
return "Yes";
else
return "No";
}
Instead of getting all the results and checking with each one of the result you directly put a condition to extract the results which satisfies your condition.This will be suggestable if you have many records.
You need to put one of the return outside of the while loop.
For example if you just wanted to check if $curval == $dbval
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
//If the condition was met return with a no
if ($curval == $dbval) {
return "no";
}
}
//If the condition was not met return yes
return yes;
That's basically what you need to do so the loop will run until your condition was met or not at all.
Not sure if this is a common problem or not, but I ran upon it. When trying to put a if/else statement into a function, it simple does not work. But when do the if/else without the function, it does work (So, I know that the if/else is correct).
I have 2 separate documents, Home.php and Functions.php here is what I have inside those files"
Home.php (the PHP)
<?php
$db = new PDO("mysql:host=localhost;dbname=TEST;charset=utf8","Xero","");
include("Functions.php");
menu();
?>
And then we have the Functions.php (the PHP)
<?php
$db = new PDO("mysql:host=localhost;dbname=TEST;charset=utf8","Xero","");
function menu() {
echo "
<div id='menu'>
<div id='user-menu'>
";
// Check AutoLogin-User then :
$getAutoUser = $db->prepare("SELECT * FROM `users-PHP_FNC` WHERE `ip`='" . $_SERVER['REMOTE_ADDR'] . "'");
$getAutoUser->execute();
if ($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC)) {
echo "
" . $autoUser['user'] . "
";
}
// If no AutoLogin-User was found:
else {
echo "
Test
";
}
echo "
</div>
</div>
";
}
?>
Not sure why this doesn't work. Are you not allowed to have if/else statements in a PHP function?
Actually, you can be sure that if ... else statements work inside the scope of a function.
Therefore, the problem lies elsewhere... But there is another thing that you should do:
// Replace this
if ($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC))
// By this
if ($autoUser == $getAutoUser->fetch(PDO::FETCH_ASSOC))
Why ?
Because when you say if ($something = $somethingElse) you tell PHP different things in a particular order:
1st => assign the current value of $somethingElse to $something
2nd => test if $something and $somethingElse share the same value
2nd becoming obviously true because of 1st.
To bypass the 1st step, simply use == in place of =.
$db is not in the function's scope. You would have to pass it in. I would make my code more like:
// connect.php - should be in a separate secure folder I'll call restricted
<?php
function db(){
return new PDO('mysql:host=localhost;dbname=TEST;charset=utf8', 'Xero', '');
}
?>
// index.php
<?php
include_once 'restricted/connect.php';
function menu(){
$db = db();
echo "<div id='menu'><div id='user-menu'>";
// Check AutoLogin-User then :
$getAutoUser = $db->prepare("SELECT * FROM `users-PHP_FNC` WHERE ip='{$_SERVER['REMOTE_ADDR']}'");
$getAutoUser->execute();
if($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC)) {
echo $autoUser['user'];
}
else{
// If no AutoLogin-User was found:
echo 'Test';
}
echo '</div></div>';
}
In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.