Catching the returned value - php

this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();

if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);

Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.

Related

Parameters to a class constructor function

I'm trying to adapt a class of mine that handles tags for events stored in a JSON file. You can create tags, delete them, restore them, view them, etc. In the code below for this library you can see that I retrieve the array from the file during the constructor function so I use it and manipulate it throughout my classes' functions.
class tagHandler {
private $tagsFile = "/home/thomassm/public_html/functions/php/tags.json";
private $LstTags;
private $LstReturn;
function __construct() {
$this->LstTags = array();
if(!file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
function __destruct(){
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
}
//More functions that use the collected array here.
I am trying to adapt the class to deal with people signed up to my events. Each event has a record in my database that will store a field for an array of males who sign up and females who sign up. I wish for the constructor class to get the arrays(s) from the record so they can be manipulated like the previous class. The issue is to get the array I have to search the DB for a record with the Event ID (EID) and that will require a variable passed to the constructor function. To make things worse, this parameter has to be able to change in a loop. For example, the page listing all the events will have to use this class in a loop going through each record, so it can retrieve the array to manipulate it and then show it in a table / fullcalendar before repeating the process to get the next event. I have put the code I have so far below. Its not complete (some variables haven't been renamed to male and female, etc) and may be completely wrong, but it will give you a base to explain from.
class signupHandler {
private $LstMaleS;
private $LstFemaleS;
private $LstReturn;
function __construct($IntEID) {
$this->LstTags = array();
$StrQuery = "SELECT MaleS, FemaleS FROM tblEvents WHERE EID = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('s',$IntEID);
$statement->execute ();
$results = $statement->get_result ();
}
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
Thanks,
Tom
function decodeNames($StrNames){
$this->LstNames = array();
$this->LstNames = json_decode($StrNames, true);
if(!$this->LstNames) $this->LstNames = array();
$this->LstNames = array_values($this->LstNames);
}
function update(){
$this->LstNames = array_values($this->LstNames);
return json_encode($this->LstNames);
}
public function addSignUp($StrNames, $StrUsername, $StrStatus){
$this->decodeNames($StrNames);
$BlnPresent = false;
for($i = 0; $i < count($this->LstNames); $i++){
if($this->LstNames[$i][0] == $StrUsername){
$this->LstNames[$i][1] = $StrStatus;
$BlnPresent = true;
}
}
if($BlnPresent == false){
array_push($this->LstNames, array($StrUsername, $StrStatus, date("Y-m-d H:i:s")));
}
return $this->update();
}
I have decided to pass the encoded JSON array to the class each time I call a function from it. Before every function it is decoded and turned into an array and at the end it is then re-encoded and returned back to the file calling it. Now I no longer have any constructor or destruct functions.

Exception information: Message: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

I have a code here that, has to search and post back information selected in a table above the add button, the search works but im having a problem with the post back to the table function. These are the lines it shows to have errors.
C:\xampp\htdocs\portal-gep-2\application\models\ServiceProviders.php(68): Zend_Db_Table_Abstract->fetchRow(Object(Zend_Db_Table_Select))
public function getName($id)
{
$select = $this->select();
$select->where('service_provider_id = ?', $id);
$result = $this->fetchRow($select); //this line
return $result['service_provider_name'];
}
#6 C:\xampp\htdocs\portal-gep-2\application\modules\admin\controllers\AjaxController.php(1104): Model_ServiceProviders->getName(NULL)
public function postserviceproviderAction()
{
$form = new Form_IndustrialTable();
$this->view->form = $form;
if(!$form->isValid($_POST))
{
$values=$form->getValues();
}
$sp = $this->getRequest()->getPost('serviceprovider', null);
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id); //this line
$rtn_array= array( 'sp' => $sp,
'serviceprovider ' => $serviceprovider);
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
echo Zend_Json::encode($rtn_array);
}
You don't put any initial value to $id so it's null which causes error.
You want SQL query to look something like SELECT * FROM service_providers WHERE service_provider_id = 50, but for this you have to provide id which you want to find (50 in this example). You need to add some value to variable $id before using in $select->where('service_provider_id = ?', $id);, but your code you never put any value to variable $id.
If I'm guessing your idea then you need to change line:
$serviceprovider = $mdlserviceprovider ->getName($id);
to:
$serviceprovider = $mdlserviceprovider ->getName($sp);
Also this part of your code probably unnecessary as it does nothing:
$form = new Form_IndustrialTable();
$this->view->form = $form;
if(!$form->isValid($_POST))
{
$values=$form->getValues(); //you never use $values
}

PHP How do you define an array and reference it in a class?

I have written a php class to use in a small script to just run any query that I like from other scripts. This is NOT going to be used publicly or in production, and I'm aware of the huge security issue this poses!
I have done this as an excercise to see learn about classes etc... I seem to be having problems with one specific line in the code which is causing an error somewhere. I think it might be because I'm trying to return an array, and I think I haven't defined it properly in the class.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
This is the whole code.
<?php
class GetRandomRecord {
//Connection
public $CUDBName;
public $CUHost;
public $CUUser;
public $CUPassword;
public $in_SQL;
public $out_Resource;
public $CULink;
public $message;
public $errors = array(); // is this correct?
public $resultOfQuery = array(); // is this correct?
/****************************************************************/
public function setSQL($value){
$this->in_SQL = $value;
return $this->in_SQL;
}
/****************************************************************/
public function setConnectionString($db,$host,$user,$password){
$this->CUDBName = $db;
$this->CUHost = $host;
$this->CUUser = $user;
$this->CUPassword = $password;
}
/****************************************************************/
public function runSQL() {
$this->CULink = mysqli_connect( $this->CUHost , $this->CUUser , $this->CUPassword , $this->CUDBName);
if (mysqli_connect_errno()) {
$this->message = "Connection failed: ".mysqli_connect_error();
return $this->message;
}
$this->out_Resource = mysqli_query($this->in_SQL , $this->CULink);
if (!$this->out_Resource)
{
$this->errors['sql'] = $this->in_SQL;
$this->errors['eeDBName'] = $this->CUDBName;
$this->errors['eeLink'] = $this->CULink;
$this->errors['status'] = "false"; //There was a problem saving the data;
mysqli_close($this->CULink);
return json_encode($this->errors);
}
else
{
// success
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
mysql_close($this->CULink);
return $this->resultOfQuery;
} // if (!mysql_query( $CUDBName , $sql , $CULink))
}
/****************************************************************/
}//class
$recordGet = new getRandomRecord();
$recordGet->setConnectionString('databasename','localhost','username','password');
// select count from database
$tableName = "userList";
$countSQL = "select count(*) from $tableName";
$recordGet->setSQL($countSQL);
$result = $recordGet->runSQL();
print_r($result);
?>
Can you help me identify the problem?
EDIT: Actually I haven't got a specific error message. I have an HTTP Error 500 which usually means my code is duff, and I narrowed it down by commenting sections of code until I found the line that caused it.
You have an extra close-paren on line 64.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
The line should be:
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC);

How to correctly return an array for further use?

I have the following code on my site:
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
$smarty->assign('results', $results);
}
It works without any problems, but now I wanted to put most of this in my database class to work more object oriented. But I have some problems returning the array. I have done this
$statusMessage = $db->getStatusMessages();
var_dump($statusMessage);
The function:
function getStatusMessage(){
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
}
return $results;
}
But this just tells me, that my array is null. so there have to be an problem with my returning. How do I do it correctly?
My database entries are statusID, posterID, statusMessage, dateTime, sumRating and sumVotes.
And what do I do if I want to also return an entry of another table? Like, I have the givenName and familyName of the poster (posterID) on another table. How do I also return this data?
Okay I got it. First of all, I made the mistake, that I - as #slugonamission said - that I made a spelling mistake in the function name. Then, I changed my forloop in the home.php from
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage[$i]);
}
to this, because the [$i] at the end made the forloop only use the last entry of the database and from that only the first letter.
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage);
}
Now what I'm working on is how to get data from other tables, too.
function getStatusMessage(){
global $db; // this is what you actually need to make function work
$sql = "SElECT s.*, username FROM statusmessages s JOIN users u ON posterID.=u.id";
$stm = $db->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
note that you have to use JOIN to get associated info
You have to parse your $db variable to your function:
function my_function() {
global $db;
// some code
}
or to use it like this:
class myClass {
private $db;
public function __construct() {
$this->db = new MySQLi("host","user","pass","db");
}
public function my_function() {
$my_db_query = $this->db->query('query');
}
}

Why is this php function causing a sever 500 error?

I'm trying to implement these two functions in a separate file functions.php and call it in index.php
function is_field($column, $table, $requested) {
$is_field_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($column, $table, $requested) {
$get_content_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$get_content_result = $mysqli->query($get_content_query);
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content_content = $get_content_row["content"];
$get_content_result->close();
return $content;
}
I have tried it over and over again and I have no idea why it wont work. The first one is returning 1 for valid or 0 for invalid. The second retrieves the content from a specific cell in the MySQL table. Any help would be much appreciated.
You're using $mysqli inside the function, but you never pass the MySQLi resource itself. Consider writing your function like this:
function is_field($mysqli, $column, $table, $requested) {
Or, create a class that takes a MySQLi resource and reference it with $this->mysqli inside your function.
Also, code like this may be another issue:
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
You're not checking whether $is_field_result is false; therefore, the next statement causes a fatal error, because a property can't be fetched from something that's not an object.
if (($is_field_result = $mysqli->query($is_field_query)) === false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
It turns out the reason it was not working was I needed to add an extra field into the function to accept the passing of $mysqli from the connection.
function is_field($mysqli, $column, $table, $requested) {
$is_field_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($is_field_result = $mysqli->query($is_field_query)) == false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($mysqli, $column, $table, $requested) {
$get_content_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($get_content_result = $mysqli->query($get_content_query)) == false) {
die($mysqli->error);
}
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content = $get_content_row["content"];
$get_content_result->close();
return $get_content;
}

Categories