Can't retrieve data in PHP API - php

I'm building a simple CRUD app as a learning exercise in Angularjs and PHP. I have a shell page, mysql backend, a PHP API that handles the SQL requests, and I'm using Angularjs to handle the flow of data between the shell page and the API. I'm working off an API modeled here:
http://angularcode.com/demo-of-a-simple-crud-restful-php-service-used-with-angularjs-and-mysql/
I've tested every component of this app so far and everything works cleanly except the API. All I've done to modify the original was change the syntax to PDO and I adjusted the response function because the existing one didn't work.
The abstract class:
<?php
class REST {
public $_allow = array();
public $_content_type = "application/json";
public $_request = array();
private $_method = "";
private $_code = 200;
public function __construct(){
$this->inputs();
}
public function get_referer(){
return $_SERVER['HTTP_REFERER'];
}
/*public function response($data,$status){
$this->_code = ($status)?$status:200;
$this->set_headers();
echo $data;
exit;
}*/
public function response($status, $status_message, $data){
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response = json_encode($response);
}
private function get_status_message(){
$status = array(
200 => 'OK',
201 => 'Created',
204 => 'No Content',
404 => 'Not Found',
406 => 'Not Acceptable');
return ($status[$this->_code])?$status[$this->_code]:$status[500];
}
public function get_request_method(){
return $_SERVER['REQUEST_METHOD'];
}
private function inputs(){
switch($this->get_request_method()){
case "POST":
$this->_request = $this->cleanInputs($_POST);
break;
case "GET":
case "DELETE":
$this->_request = $this->cleanInputs($_GET);
break;
case "PUT":
parse_str(file_get_contents("php://input"),$this->_request);
$this->_request = $this->cleanInputs($this->_request);
break;
default:
$this->response('',406);
break;
}
}
private function cleanInputs($data){
$clean_input = array();
if(is_array($data)){
foreach($data as $k => $v){
$clean_input[$k] = $this->cleanInputs($v);
}
}else{
if(get_magic_quotes_gpc()){
$data = trim(stripslashes($data));
}
$data = strip_tags($data);
$clean_input = trim($data);
}
return $clean_input;
}
private function set_headers(){
header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
header("Content-Type:".$this->_content_type);
}
}
?>
And the API itself:
<?php
require_once("Rest.inc.php");
class API extends REST {
public $data = "";
private $db = NULL;
private $conn = NULL;
public function __construct(){
parent::__construct();
$this->dbConnect();
}
/*
* Connect to Database
*/
private function dbConnect(){
$this->conn = null;
$servername="myServer";
$dbname="mySQL";
$username="myUN";
$password="myPW";
try{
$this->conn = new PDO("mysql:host=$servername;Database=$dbname",$username, $password);
}catch(PDOException $e){
echo "Failed:" . $e->getMessage();
}
return $this->conn;
}
/*
* Dynmically call the method based on the query string
*/
public function processApi(){
//$func = strtolower(trim(str_replace("/","",$_REQUEST['x']))); //<<--NEED TO FIX THIS. x determines which function to call
$func = 'quote';
if((int)method_exists($this,$func) > 0){
$this->$func();
}else{
$this->response(404,'','');
}
}
private function quote(){
if($this->get_request_method() != "GET"){
$this->response(406, '', '');
}
$id = (int)$this->_request['id'];
if($id > 0){
try{
$sql = "SELECT * FROM mysql.Quotes WHERE ID =:ID";
$query = $this->conn->prepare($sql);
$query->bindParam(":ID", $id);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}catch(PDOException $e){
echo "Failed:" . $e->getMessage();
}
echo $this->response(200,"Success",$result);
}
}
// Initiate Library
$api = new API;
$api->processApi();
?>
One issue I'm aware of is that the commented portion in processAPI() does not work. It's supposed to grab the initial part of the URL and determine which function to run based on based on that, but my server keeps throwing an error. My workaround for the time being is just to hard-code $func = 'quote';
More importantly, though, the API returns an empty object whenever it runs. It connects to the DB and executes without errors, and it does return an object as designed -- there just isn't anything inside it. If I pull out the core components -- the DB connection, the SQL request, and the response function -- and run them on their own, they correctly pull the data and pass it on to the shell. So something in the REST class or the API must be fouling it up, but I'm not handy enough in PHP yet to figure out where it's going wrong. I'd appreciate any feedback.

Related

Creating a Cursor Based Pagination System in PHP

I am trying to figure out how how to create my own simple cursor based pagination system in PHP and am having difficulty trying to understand how star starting_after and starting_before works as mentioned in this medium.com post for how the company stripe deals with cursor pagination. In my case I am using the id column that is in ascending order to hopefully make this work. The issue that I am having is getting an id for the first "page". Currently my first page would direct to the second page since starting_after leads to the next page and not the currently page. Any advice for how to build this out would be awesome. I already created page based pagination, but think that cursor pagination would be more useful for most of my cases.
I have attached the two files that I have created thus far to try to get this to work.
Pagination class
<?php
require_once "DB.php";
class New_Pagination {
private $table = "";
private $limit;
private $starting_after = "";
private $starting_before = "";
private $db;
public function __construct() {
$this->db = DB::getInstance();
}
public function getLimit(): int {
return $this->limit;
}
public function setLimit(int $limit): void {
$this->limit = $limit;
}
public function getStartingAfter(): string {
return $this->starting_after;
}
public function setStartingAfter(string $starting_after): void {
$this->starting_after = $starting_after;
}
public function getStartingBefore(): string {
return $this->starting_before;
}
public function setStartingBefore(string $starting_before): void {
$this->starting_before = $starting_before;
}
public function getTable(): string {
return $this->table;
}
public function setTable(string $table): void {
$this->table = $table;
}
public function idExists($id) {
$result = $this->db->find(self::getTable(), [
"select" => "id",
"conditions" => "id = $id",
"fetchType" => "single"
]);
if (empty($result)) {
return FALSE;
} else {
return $result->id;
}
}
public function getData($starting_after, $starting_before) {
self::setStartingAfter($starting_after);
self::setStartingBefore($starting_before);
$starting_after = self::getStartingAfter();
$starting_before = self::getStartingBefore();
$data = [];
$order = !empty($starting_after) ? "ASC" : "DESC";
if (empty($starting_after) && empty($starting_before)) {
$data["data"] = $this->db->find(self::getTable(), [
"select" => "*",
"order" => "id ASC",
"limit" => self::getLimit(),
"fetchType" => "all"
]);
} else {
$data["data"] = $this->db->find("carousel_image", [
"select" => "*",
"conditions" => "id >= '$starting_after' OR id <= '$starting_before'",
"order" => "id $order",
"limit" => self::getLimit(),
"fetchType" => "all"
]);
}
$next = self::idExists($data["data"][count($data["data"]) - 1]->id + 1);
$previous = self::idExists($data["data"][0]->id - 1);
$data["cursor"] = [
"next" => $next,
"previous" => $previous
];
return $data;
}
public function generateLink() {
$test = self::getData("", "");
$test2 = [];
$test2[0] = $test;
$i = 0;
do {
$test2[$i] = $test;
$test = self::getData($test["cursor"]["next"], "");
$i++;
$test2[$i] = $test;
} while ($test["cursor"]["next"] !== FALSE);
$test2[$i] = $test;
echo "<ul>";
$j = 1;
foreach ($test2 as $key => $val) {
if ($val["cursor"]["next"] !== FALSE) {
$url = "/process.php?starting_after=" . $val["cursor"]["next"];
echo "<li>";
echo "<a href='$url'>$j</a>";
echo "</li>";
$j++;
}
}
echo "<ul>";
}
}
Test file
$pagination = new New_Pagination();
$pagination->setLimit(2);
$pagination->setTable("carousel_image");
echo "<pre>";
$pagination->generateLink();
echo "</pre>";
The cursors are useful to prevent scan big tables and allow to move in very big sources (files, external resources, etc., etc.). In the majority of the cases, cursors are provided by binary libraries and supported by the core of the related system (mysql, files). If you try to emulate this behavior in not natural way you must take care because you could add overhead and get unexpected results.
In the other hand, is very useful to have a pagination class, but be aware, this class have some problems.
getData is very expensive because it performs 3 queries to get a batch of results
the class is too verbose, the getters and setters add too much noise
the results are sorted using very rare criteria. Remember, if you are in search results you need the same order moving to the next page and moving to the previous page
My suggestions...
Create interfaces
<?php
interface CursorAble {
public function fetchNext ($startingAfter);
public function fetchPrev ($startingBefore);
public function getPreviousLink ();
public function getNextLink ();
}
interface Pageable {
public function getCollectionSize ();
public function getPageSize ();
public function getPagesCount ();
public function getPageLinks ();
}
When you create interfaces you ensures that the classes expose the desired behavior and furthermore delegate the specialized details to the concrete implementations. The concrete implementations can define it dependencies in the constructor, something very good when you relies on dependency injection.
CursorAble implementation example
<?php
class PdoCursorAbleTable implements CursorAble {
private $pdo;
private $table;
private $results;
private $pageSize;
public function __construct (PDO $pdo, $table, $pageSize = 100) {
$this->pdo = $pdo;
$this->table = $table;
$this->pageSize = (int)$pageSize ?: 100;
}
public function fetchNext ($startingAfter) {
$s = $this->pdo->prepare("select * from {$this->table} where id > :starting_after limit {$this->pageSize}");
$s->bindValue(':starting_after', $startingAfter, PDO::PARAM_INT);
$s->execute();
$this->results = $s->fetchAll() ?: [];
return $this->results;
}
public function fetchPrev ($startingBefore) {
$s = $this->pdo->prepare("select * from {$this->table} where id < :starting_before limit {$this->pageSize}");
$s->bindValue(':starting_before', $startingBefore, PDO::PARAM_INT);
$s->execute();
$this->results = $s->fetchAll() ?: [];
return $this->results;
}
public function getPreviousLink () {
return !$this->results ? '' : '?starting_before=' . $this->results[0]->id;
}
public function getNextLink () {
if (!$this->results || count($this->results) < $this->pageSize) return '';
return '?starting_after=' . $this->results[count($this->results)]->id;
}
}
And the Pageable example
<?php
class PdoPageableTable implements Pageable {
private $pdo;
private $table;
private $pageSize;
private $collectionSize;
public function __construct (PDO $pdo, $table, $pageSize = 100) {
$this->pdo = $pdo;
$this->table = $table;
$this->pageSize = $pageSize;
}
public function getCollectionSize () {
if ($this->collectionSize === null) {
$s = $this->pdo->prepare("select count(id) from {$this->table}");
$s->execute();
$this->collectionSize = $s->fetchColumn('0');
}
return $this->collectionSize;
}
public function getPageSize () {
return $this->pageSize;
}
public function getPagesCount () {
return ceil($this->collectionSize / $this->getPageSize());
}
public function getPageLinks () {
$pages = [];
foreach (range(1, $this->getPagesCount()) as $page) {
$pages[] = '?page=' . $page;
}
return $pages;
}
}
The test file
<?php
$pagination = new PdoCursorAbleTable($pdo, 'carousel_image', 2);
echo "<pre>";
$startingAfter = 0;
$results = $pagination->fetchNext($startingAfter);
foreach ($results as $result) {
// do something
}
echo $pagination->getNextLink();
echo "</pre>";

PHP api rest router issue

To test my android application in a more concrete way, and since my company has no API yet, I decided to "create" it in a simplified way for testing purpose (and learning, i'm only an intern).
The Android app uses Retrofit.
Anyway, I followed one tutorial for a "login" method, where I use the "Post" method in android, passing login and password as #field datas, and everything worked fine, I could retrieve the data in my android app and log in (I do not manage security yet, this will be added later when they hire a devOp)
The problem is after that I wanted to create a Router for more complicated urls (like "/model/client/:id/contracts") and now nothing work anymore. I do not use framework, only composer. I end my internship in two days I do not really have time to learn a big thing.
So, here are the classes that were working before I make the router :
/src/Model/client/login.php :
<?php
namespace App\Model\client;
// required headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: access');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
// include database and object files
include_once 'src/config/Database.php';
include_once 'src/Model/client/client.php';
// Instantiate database and connect
$database = new Database();
$db = $database->connect();
// prepare product object
$client = new Client($db);
console.log("Login launched");
// set ID property of record to read
$client->login = isset($_POST['login']) ? $_POST['login'] : die();
$client->password = isset($_POST['password']) ? $_POST['password'] : die();
// read the details of product to be edited
$result = $client->readOne();
$num = $result->rowCount();
//Check if corresponding client
if($num>0){
if($client->city==3){
$client->city = "Valenciennes";
}
$row = $result->fetch(PDO::FETCH_ASSOC);
if($row['city']==3){
$city = "Valenciennes";
} else {$city='randomname';}
$client->id = $row['id'];
$client->login = $row['login'];
$client->raison = $row['raison'];
$client->addr1 = $row['addr1'];
$client->addr2 = $row['addr2'];
$client->city = $city;
$client->telephone = $row['telephone'];
$client->portable = $row['portable'];
$client->fax = $row['fax'];
$client->email = $row['email'];
$client->tva_intra = $row['tva_intra'];
$client->siret = $row['siret'];
$client->gtr = $row['gtr'];
$client->password = $row['password'];
// create array
$logged_client = array(
'id' => $client->id,
'login'=> $client->login,
'raison' => $client->raison,
'addr1' => $client->addr1,
'addr2' => $client->addr2,
'city' => $client->city,
'telephone'=>$client->telephone,
'portable'=>$client->portable,
'fax'=>$client->fax,
'email'=>$client->email,
'tva_intra'=>$client->tva_intra,
'siret'=>$client->siret,
'password'=>$client->password);
// set response code - 200 OK
http_response_code(200);
// make it json format
echo json_encode($logged_client);
}
else {
// set response code - 404 Not found
http_response_code(404);
// tell the user product does not exist
echo json_encode(array("message" => "Client does not exist.".$client->login));
}
?>
The class of the object I need to retrieve (src/Model/client/client):
<?php
class Client{
//db stuff
private $cnx;
private $table_name='client';
//client properties
public $id;
public $login;
public $nom;
public $raison;
public $addr1;
public $addr2;
public $city;
public $telephone;
public $portable;
public $fax;
public $email;
public $tva_intra;
public $siret;
public $gtr;
public $password;
//constructor
public function __construct($db){
$this->cnx = $db;
}
//GetOne ###########################################################################
function readOne(){
$query = 'SELECT * FROM '.$this->table_name.' WHERE login = ? AND password = ?';
// prepare query statement
$stmt = $this->cnx->prepare($query);
// bind id of product to be updated
$stmt->bindParam(1, $this->login);
$stmt->bindParam(2, $this->password);
// execute query
$stmt->execute();
// get retrieved row
return $stmt;
}
}
?>
The database exists, here is the connection and it worked fine :
<?php
class Database {
//DB Params
private $host='localhost';
private $db_name='techcrea';
private $username = 'root';
private $pwd = '';
private $cnx;
//DB Connect
public function connect(){
$this->cnx = null;
try {
$this->cnx = new PDO('mysql:host='.$this->host.';dbname='. $this->db_name, $this->username,$this->pwd);
$this->cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Connection Error:'.$e->getMessage();
}
return $this->cnx;
}
}
So here are the problems starting : this are the classes I added and now nothing works anymore, I get router exception errors (no matching routes) etc..., not only in my android app that returns an "onfailure" response, but also when i try the url in my navigator :
1 - Index :
<?php
require 'vendor/autoload.php';
$router= new App\Router\Router($_GET['url']);
$router->get('/', function(){
echo "homepage";
});
$router->post('/Model/client/login', function(){
//require_once 'src/Model/client/login.php';
});
$router->get('/Model/client/:id/contrats', function($id){
echo "contrats";
});
$router->run();
2 - Router
<?php
namespace App\Router;
class Router {
private $url;
private $routes =[];
private $namedRoutes= [];
public function __construct($url){
$this->url = $url;
}
public function get($path, $callable, $name =null){
return $this->add($path,$callable,$name,'GET');
}
public function post($path, $callable, $name=null){
return $this->add($path,$callable,$name,'POST');
}
public function patch($path, $callable, $name=null){
return $this->add($path,$callable,$name,'PATCH');
}
public function put($path, $callable, $name=null){
return $this->add($path,$callable,$name,'PUT');
}
public function delete($path, $callable, $name=null){
return $this->add($path,$callable,$name,'DELETE');
}
private function add($path, $callable,$name,$method){
$route = new Route($path, $callable);
$this->routes[$method][]= $route;
if($name){
$this->namedRoutes[$name] = $route;
}
return $route;
}
public function url($name,$params = []){
if(!isset($this->namedRoutes[$name])){
throw new RouterException("no match name route");
}
$this->namedRoutes[$name]->getUrl($params);
}
public function run(){
if(!isset($this->routes[$_SERVER['REQUEST_METHOD']])){
throw new RouterException('request method does not exist');
}
foreach($this->routes[$_SERVER['REQUEST_METHOD']] as $route){
if($route->match($this->url)){
return $route->call();
}
}
throw new RouterException('no matching routes');
}
}
3 - Route
namespace App\Router;
class Route {
private $path;
private $callable;
private $matches = [];
private $params = [];
public function __construct($path, $callable){
$this->path = trim($path,'/');
$this->callable = $callable;
}
public function with($param, $regex){
$this->params[$param] = str_replace('(','(?:', $regex);
return $this;
}
public function match($url){
$url=trim($url, '/');
$path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->path);
$regex = "#^$path$#i";
if(!preg_match($regex, $url, $matches)){
return false;
}
array_shift($matches);
$this->matches= $matches;
return true;
}
public function call(){
if(is_string($this->callable)){
$params = explode('#', $this->callable);
$controller = "App\\Controller\\".$params[0]."Controller";
$controller = new $controller();
$action = $params[1];
return $controller->$action();
} else {
return call_user_func_array($this->callable, $this->matches);
}}
private function paramMatch($match){
if(isset($this->params[$match[1]])){
return '('.$this->params[$match[1]].')';
}
return '([^/]+)';
}
public function getUrl($params){
$path = $this->path;
foreach($params as $k=>$v){
$path= str_replace(":$k",$v, $path);
}
return $path;
}
}
and the htaccess doc :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
Thank you very much if you help me

Passing array of Objects in php 7.3

Hi there still new to PHP and struggling with something really basic and it's frustrating me cause I can't see the error. I have read the PHP manual on passing array of objects.
class Customer{
public $companyId;
public $customerId;
public $name;
public function __construct($companyId,$customerId,$name)
{
$this->companyId = $companyId;
$this->customerId = $customerId;
$this->name = $name;
}
}
class CustomersDB
{
...
/**
* #return Customer[]
*/
public function getCustomers($search_str): array {
$resultObj = array();
$result = NULL;
try {
if (! $this->db) {
die('Database handle not defined') ;
}
if ($search_str && ! empty($search_str)) {
$result = $this->ListCustomers(Utils::COMPANY_ID, $search_str, $this->db);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$_tmp = new Customer($row['CompanyID'],
$row['CustomerID'],
$row['CustomerName']);
// $resultObj.push($_tmp);
$resultObj[] = $_tmp;
}
}
} catch (Exception $e) {
// echo Utils::logMsgtoWeb($e->getTraceAsString());
} finally {
$result = NULL;
}
return $resultObj;
}
}
use Respect\Rest\Routable;
class Customers implements Routable {
/**
*
* Can pass in a partial string to search for a customer
* or pass in an ID for a specific match.
*/
public function get($searchStr){
// header('Content-type: application/json');
$result = $this->custdb.getCustomers($searchStr); // ERRORS HERE
if ($result && ! empty($result)) {
return json_encode( $result);
} else {
return NULL;
}
}
}
I get this error: PHP Recoverable fatal error: Object of class Scheduler\db\CustomersDB could not be converted to string in Customers.php.
Any help would be appreciated.

MySQL randomly assigns second port / PHP

My MySQL randomly assigns a second port to the requested address like this:
[2002] Cannot assign requested address (trying to connect via tcp://127.0.0.1:3306:3306)
This behavior is triggered on my localhost and on my servers as well, so I figured it might be my code. I'm connecting via a self-written class, which is using constants only to connect (which are correct, no second ports assigned within these constants), so I'm pretty clueless why this behavior is triggered sometimes and where the second port comes from. The execution of the script terminates when this error occurs.
I added the class to this post, if someone wants to browse through.
Any advise is welcome to fix or circumnavigate this.
Thanks in advance!
class mysql{
protected $query = false;
protected $lastquery = false;
protected $result = false;
protected $row = false;
protected $args = array('');
protected static $mysqli = null;
public function __construct(\mysqli $mysqli = null){
self::$mysqli = $mysqli;
$this->establishAutoConnection();
}
// Tries to establish connection, if none is set.
protected function establishAutoConnection(){
IF(empty(self::$mysqli)):
SWITCH($_SERVER['SERVER_NAME']):
case 'localhost':
self::$mysqli = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_DATABASE);
break;
case 'AN IP.IP.IP':
$this->connectToSlave();
break;
default:
self::$mysqli = new mysqli(MYSQL_HOST_SERVER, MYSQL_USER_SERVER, MYSQL_PASSWD_SERVER, MYSQL_DATABASE_SERVER);
ENDSWITCH;
ENDIF;
}
public function connectToSlave(){
self::$mysqli = new mysqli(SLAVE_HOST_SERVER, SLAVE_USER_SERVER, SLAVE_PASSWD_SERVER, SLAVE_DATABASE_SERVER);
}
public function connectToMaster(){
self::$mysqli = new mysqli(MASTER_HOST_SERVER, MASTER_USER_SERVER, MASTER_PASSWD_SERVER, MASTER_DATABASE_SERVER);
}
// Sets the PDO arguments, which need to be replaced by '?'
public function setArgs(&$data, $type = false){
$type = $type ?: $this->getTypeString($data);
$this->args[0] .= $type;
$this->args[] = &$data;
return $this;
}
// Reset function needs to be called in order to make a new query.
public function reset(){
$this->args = array('');
$this->row = false;
$this->result = false;
return $this;
}
// Loops through the found results.
public function loopThroughResults(){
return ($this->row = $this->result->fetch_assoc())
? true
: false;
}
// Returns the row unformatted. If no result is found an emtpy array is returned.
public function getRow(){
$this->row = $this->row ?: $this->result->fetch_assoc();
return $this->row ?: array();
}
// Returns the first result of the first row.
public function getSingleResult(){
FOREACH($this->getRow() as $assoc => $value):
return $value ?: false;
ENDFOREACH;
return false;
}
// Returns the result by rowname
public function getByName($name){
return isset($this->row[$name])
? $this->row[$name]
: false;
}
// If a new query is made, while the former query has not been resetted, a warning is stored or an error is thrown.
protected function isResetted(){
IF($this->result):
$this->warning("PDO has not been resetted from query: ". $this->lastquery ." // new query: ". $this->query);
ENDIF;
}
// Executes the prepared query.
public function query($sql){
$this->query = $sql;
$this->isResetted();
$this->lastquery = $sql;
IF($prep = self::$mysqli->prepare($this->query)):
IF(count($this->args) > 1):
call_user_func_array(array($prep, 'bind_param'), $this->args);
ENDIF;
$prep->execute();
$this->result = $prep->get_result();
$prep->close();
ELSE:
$this->error("Query $sql failed to prepare.");
ENDIF;
}
// Automatically generates the string of types for the submitted params if not set. ("ssisdss") etc.
protected function getTypeString($string){
SWITCH(gettype($string)):
case 'string':
return 's';
case 'double':
return 'd';
case 'boolean':
case 'integer':
return 'i';
case 'array':
$this->error('Unserialized array submitted to PDO.');
break;
default:
$this->error('Unknown param type submitted to PDO. ' . print_r($string) . ' type: ' . gettype($string));
break;
ENDSWITCH;
}
protected function error($msg){
IF(!new error($msg)):
trigger_error($msg);
ENDIF;
}
protected function warning($msg){
IF(!new warning($msg)):
trigger_error($msg);
ENDIF;
}
}
Did you added the port number in your definition? So e.g.
MYSQL_HOST = 127.0.0.1:3306
MYSQL_HOST_SERVER = 127.0.0.1:3306
mysqli will use his default port settings on your server definition. So if you add the port number here, the result will be the same as your request error:
MYSQL_HOST = 127.0.0.1:3306:3306
MYSQL_HOST_SERVER = 127.0.0.1:3306:3306

PDO Binding Sequence/MySQL Incompatibility?

I'm using MySQL(i)-community-5.3 if not mistaken. After finally getting the hang of PDO, I can now conclude that the infected sectore is that which processes binding, all other functions are fine (that I know of). Below I will present a function which works and also doesn't work (the sequence without anything to do with binding works flawlessly.
Function you() is as followes:
public function you($row) {
if(isset($_COOKIE["SK"])) {
$usr = $this->baseXencode($_SESSION["username"]);
$q = "SELECT $row FROM SN_users WHERE username=:USR";
$this->netCore->q($q);
$this->netCore->bind(":USR", $usr);
$result = $this->netCore->single();
$result = $result[$row];
} else {
$q = "SELECT $row FROM SN_users WHERE username='".$this->baseXencode("Anonymous")."' AND password='".$this->baseXencode("Anonymous")."'";
$result = $this->netCore->q($q);
$result = $this->netCore->single();
$result = $result[$row];
}
return $result;
}
}
(As you can see, when pre-allocating the username/password combo for Anonymous users, the function executes perfectly whereas binding within the if() section does not, returning the value 1.
Below is my binding function bind() (if you may require any other code, I will edit this post further~^^):
EDIT:
Below is the netCore class:
class netCore {
private $boot;
private $dbHost = "";
private $dbNAME = "";
private $dbPASS = "";
private $dbUSR = "";
private $err;
private $state;
public function __construct() {
$bootloadr = "mysql:host=".$this->dbHost.";dbname=".$this->dbNAME.";charset=UTF8";
$opt = array(PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$this->boot = new PDO($bootloadr, $this->dbUSR, $this->dbPASS, $opt);
} catch(PDOException $e) {
$this->err = "<b>Lebensborn® netCore™ Error:</b> An exception has been raised during Network-to-Database procedures.<br /><b>Message:</b> ".$e->getMessage().".";
}
}
public function bind($param, $value, $type = NULL) {
if(is_null($type)) {
switch(true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->state->bindParam($param, $value, $type);
}
public function debug() {
return $this->state->debugDumpParams();
}
public function exe() {
return $this->state->execute();
}
public function count() {
$this->exe();
return $this->state->fetchColumn();
}
public function q($q) {
$this->state = $this->boot->prepare($q);
}
public function set() {
$this->exe();
return $this->state->fetchAll(PDO::FETCH_ASSOC);
}
public function single() {
$this->exe();
return $this->state->fetch(PDO::FETCH_ASSOC);
}
public function transBegin() {
return $this->boot->beginTransaction();
}
public function transCancel() {
return $this->boot->rollBack();
}
public function transEnd() {
return $this->boot->commit();
}
}

Categories