How To Get Values Out of An Array Inside Of A Class - php

I have a form that is passing array values to create_parts.php, then I am trying to pass those values to the parts class to insert into the database. At this point I am just lost... The form passes to create_parts.php, I can echo the results of the of the array. However in my class I cant get any values thus, my insert into the database is just a bunch of NULL.
<?php
include_once '../config/database.php';
include_once '../objects/parts_object.php';
$database = new Database();
$db = $database->getConnection();
$parts= new parts($db);
$parts->est_part_idArr=$_POST['est_part_id'];
$parts->part_qtyArr=$_POST['part_qty'];
$parts->part_numArr=$_POST['part_num'];
$parts->part_discArr=$_POST['part_disc'];
$parts->part_costArr=$_POST['part_cost'];
$parts->create();
I am able to to echo out the results here and get
{"est_part_idArr":["123","124"],"part_qtyArr":["4","6"],"part_numArr":
["2334","3344"],"part_discArr":["part","parts"],"part_costArr":["56","33"]
and echo the $stmt
{"queryString":"INSERT INTO \r\n partsT\r\n SET \r\n est_part_id=:est_part_id, part_qty=:part_qty, part_num=:part_num, part_disc=:part_disc, part_cost=:part_cost"}
However in part_object.php I cant get anything to work. I can it to insert to the database but it is all NULL.
class parts{
private $conn;
private $table_name = "partsT";
public $est_part_idArr;
public $part_qtyArr;
public $part_numArr;
public $part_discArr;
public $part_costArr;
public function __construct($db){
$this->conn = $db; }
function create(){
$query = "INSERT INTO
" . $this->table_name . "
SET
est_part_id=:est_part_id, part_qty=:part_qty, part_num=:part_num, part_disc=:part_disc, part_cost=:part_cost";
$stmt = $this->conn->prepare($query);
if(!empty($this->$est_part_idArr)){
for ($i = 0; $i < count($this->$est_part_idArr); $i++) {
if(!empty($this->$est_part_idArr[$i])){
$est_part_id = $this->$est_part_idArr[$i];
$part_qty = $this->$part_qtyArr[$i];
$part_num = $this->$part_numArr[$i];
$part_disc = $this->$part_discArr[$i];
$part_cost = $this->$part_costArr[$i];
$stmt->execute(array(
':est_part_id' => $est_part_id,
':part_qty' => $part_qty,
':part_num' => $part_num,
':part_disc' => $part_disc,
':part_cost' => $part_cost));
}
}
}
$this->est_part_idArr=htmlspecialchars(strip_tags($this->est_part_idArr));
$this->part_qtyArr=htmlspecialchars(strip_tags($this->part_qtyArr));
$this->part_numArr=htmlspecialchars(strip_tags($this->part_numArr));
$this->part_discArr=htmlspecialchars(strip_tags($this->part_discArr));
$this->part_costArr=htmlspecialchars(strip_tags($this->part_costArr));
$stmt->bindParam(":est_part_id", $this->est_part_idArr[0]);
$stmt->bindParam(":part_qty", $this->part_qtyArr[0]);
$stmt->bindParam(":part_num", $this->part_numArr[0]);
$stmt->bindParam(":part_disc", $this->part_discArr[0]);
$stmt->bindParam(":part_cost", $this->part_costArr[0]);
if($stmt->execute()){
return true;
}else{
return false;
}
}
At this point I know
public $est_part_idArr;
public $part_qtyArr;
public $part_numArr;
public $part_discArr;
public $part_costArr;
is wrong I just cant get anything to work.

You are missing some $this in front of your variables to access your public class members. Let us take this line for example:
$est_part_id = $est_part_idArr[$i];
which in my opinion should look like this:
$est_part_id = $this->est_part_idArr[$i];
On the other hand when you bind your parameters some lines down the code you're using something like this:
$stmt->bindParam(":est_part_id", $this->est_part_id);
Which I believe should be
$stmt->bindParam(":est_part_id", $this->est_part_idArr);
or
$stmt->bindParam(":est_part_id", $this->est_part_idArr[0]);

Related

How to fix get request returning nothing in Postman?

I'm learning REST API basic create, read, delete and update using pure PHP with no framework (i have no prior knowledge of REST API and this is my first time trying to get into it and learn it) and i have a strange problem with GET request not returning results with one property on and off when reading data,
read.php
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Capteur.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate capteur object
$capteur = new Capteur($db);
// Capteur read query
$result = $capteur->read();
// Get row count
$num = $result->rowCount();
// Check if any categories
if($num > 0) {
// Cat array
$cap_arr = array();
$cap_arr['data'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$cap_item = array(
'id' => $id,
'code_capteur' => $code_capteur,
'etat' => $etat,
'etab' => $etab,
'created_at' => $created_at,
'updated_at' => $updated_at
);
// Push to "data"
array_push($cap_arr['data'], $cap_item);
}
// Turn to JSON & output
echo json_encode($cap_arr);
} else {
// No Categories
echo json_encode(
array('message' => 'No Categories Found')
);
}
when i remove 'etab' => $etab it outputs data fine
This is my class:
Capteur.php
<?php
class Capteur {
// DB stuff
private $conn;
private $table = 'capteurs';
// Post Properties
public $id;
public $code_capteur;
public $etat;
public $etab;
public $created_at;
public $updated_at;
// Constructor with DB
public function __construct($db) {
$this->conn = $db;
}
// Get Posts
public function read() {
// Create query
$query = 'SELECT * FROM ' . $this->table . '
ORDER BY
created_at DESC';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
return $stmt;
}
}
?>
this is my database structure:
output:

PHP Method in Class not returning data from database

Ok this should be fairly simple.
I have a table which contains content of 3 different textboxes the method inside my class should get the content to insert into textboxes.
Example TextBoxes (TextArea) where content should be entered.
My Method
public function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array('Low' => $box['boxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
}//function
Here is my table (image below) so data / content from table should get inserted into the textboxes.
So when I do a test on content.php where I call the class method as such:
require_once('../classes/class.content.php');
$boxes = new Contents();
$boxes->LoadBoxes();
var_dump($boxes);
I get the following back:
Problem
As can be seen the array keys get returned however the data from database is not matched to array keys or returned by the method...I am stumped and have no idea what I am doing wrong here?
Any suggestions where I am going wrong? Could it be that I am not connecting to database correctly?
However if it was a database connection error I believe I would have received an error
Please keep in mind im a student and still learning.
UPDATE
Connection Schema
class Db {
private static $instance = NULL;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!isset(self::$instance)) {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
self::$instance = new PDO('mysql:host=localhost;dbname=beta', 'root', '', $pdo_options);
}
return self::$instance;
}
}
UPDATE 2
I just did the following on a test.php page which returned correct results.
require('connection.php');
function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$box[] = array('Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $box;
}//function
print_r(LoadBoxes());
?>
2 issues primary issues;
You're returning $data from the class but not populating a variable with the returned array.
You are var dumping the object itself.
This should work;
require_once('../classes/class.content.php');
$boxes = new Contents();
$data = $boxes->LoadBoxes();
var_dump($data);

Catching the returned value

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.

Having issue with oop and pdo in php

I have a form on a website. This form collects data about an EVENT. The event has 20 fields besides the ID that are in the table that corresponds to the event.
Before I was just taking the ($_POST['submit']) and if true, inserting the event fields into the database using mysql_query.
Now I'm trying to use oop and this pdo and I've pretty much defeated myself at this point. I am sure I'm doing lots of things wrong.
<?php
$str = $_SERVER['DOCUMENT_ROOT'];
include $str."/wp-config.php";
$config['db'] = array(
'host' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASSWORD,
'dbname' => DB_NAME,
'charset' => DB_CHARSET
);
$db = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname'].';charset='.$config['db']['charset'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDF::ATTR_EMULATE_PREPARES, false);
class match extends event {
public $_matchno;
public $_completed;
function __construct() {
$this->_completed = "N";
}
public function addMatch($matchno) {
$sql = $db->prepare("INSERT INTO wp_hue5gf_match_details (matchno, event_name, dateofmatch, fighttype, comp, matchref, fightclass)
VALUES (".$matchno.", $this->_eventname, $this->_doe, $this->_status, $this->_completed, $this->_refree, $this->_fightclass)");
$sql->execute();
}
}
class event {
public $_promouser;
public $_eventname;
public $_fightclass;
public $_no_of_matches;
public $_status;
public $_doe;
public $_venue;
public $_city;
public $_state;
public $_zip;
public $_sanc_body;
public $_doctor;
public $_refree;
public $_referee2;
public $_judge;
public $_judge2;
public $_judge3;
public $_boxcomm;
public $_descript;
function __construct() {
$this->_promouser = $_SESSION['username'];
$this->_eventname = $_POST['ename'];
$this->_fightclass = $_POST['efightclass'];
$this->_no_of_matches = $_POST['no_of_matches'];
$this->_status = $_POST['estatus'];
$this->_doe = $_POST['year']."-".$_POST['month']."-".$_POST['day'];
$this->_venue = $_POST['venue'];
$this->_city = $_POST['city'];
$this->_state = $_POST['state'];
$this->_country = $_POST['country'];
$this->_zip = $_POST['zip'];
$this->_sanc_body = $_POST['sbody'];
$this->_doctor = $_POST['doctor'];
$this->_refree = $_POST['refree'];
$this->_referee2 = $_POST['refree2'];
$this->_judge = $_POST['judge'];
$this->_judge2 = $_POST['judge2'];
$this->_judge3 = $_POST['judge3'];
$this->_boxcomm = $_POST['boxcom'];
$this->_descript = $_POST['descript'];
}
public function insertEvent() {
$sql = $db->prepare("INSERT INTO event (promouser, eventname, fightclass, no_of_matches, status, doe, venue, city, state, country, zip,
sanc_body, doctor, refree, referee2, judge, judge2, judge3, boxcomm, descript) VALUES ($this->_promouser, $this->_eventname, $this->_fightclass, $this->_no_of_matches, $this->_status, $this->_venue,
$this->_city, $this->_state, $this->_country, $this->_zip, $this->_sanc_body, $this->_doctor, $this->_refree, $this->_referee2, $this->_judge, $this->_judge2, $this->_judge3, $this->_boxcomm, $this->_descript)");
$sql->execute();
}
}
?>
So that is my class page. Now to the add event page. I am clearly doing something way wrong. And I have no idea where to start.
<?php
require_once(bloginfo( 'template_url' ).'/definedClasses.php');
if($_POST['submit'])
{
$event = new event();
event::insertEvent();
for($y=1;$y<= $event->_no_of_matches;$y++)
{
$match = new match();
match::addMatch($y);
}
}
?>
<form name="addevent" method="post" action="" enctype="multipart/form-data" >
<!-- The form here with all these inputs for the post values -->
</form>
I'm sure I'm trying to do too much at once. I should probably trim this down to a much smaller problem then work through it. But I have no clue where to start. I'm not looking for you to do this for me, I am looking for some guidance on what I don't understand and. I'm pretty sure it has something to do with the PDO. if this was mysql_ like it used to be I have a feeling that I would have it running right.
Thanks for taking a peek.
You can't use $db in your classes because they don't know it exists.
What is dependency injection?
Pass the PDO object as a parameter in your constructor
function __construct( PDO $db ) {
$this->$db = $db;
}
Then use $this->db instead of $db
Also use $event->insertEvent() instead of using it statically.
A better approach would be
$event = new Event( $_POST );
$eventSaver = new EvenSaver( $db ); //Name is stupid but you get it
$eventSaver->saveEvent( $event );
but that's for a different time.

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

Categories