Trying to get property of non-object CRUD - php

I am making a CRUD system for blog publications, but it's kinda strange, another developer (with more experience) looked to my coded and for him it's all right too, but this error (Notice: Trying to get property of non-object in C:\xampp\htdocs\genial\painel\inc\database.php on line 32) remains appearing.
My database code:
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
function open_database() {
try {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $conn;
} catch (Exception $e) {
echo $e->getMessage();
return null;
}
}
function close_database($conn) {
try {
mysqli_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
}
function find( $table = null, $id = null ) {
$database = open_database();
$found = null;
try {
if ($id) {
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_assoc();
}
}
else {
$sql = "SELECT * FROM " . $table;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
}
} catch (Exception $e) {
$_SESSION['message'] = $e->GetMessage();
$_SESSION['type'] = 'danger';
}
close_database($database);
return $found;
}
function find_all( $table ) {
return find($table);
}
function save($table = null, $data = null) {
$database = open_database();
$columns = null;
$values = null;
//print_r($data);
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ",";
$values .= "'$value',";
}
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro cadastrado com sucesso.';
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
function update($table = null, $id = 0, $data = null) {
$database = open_database();
$items = null;
foreach ($data as $key => $value) {
$items .= trim($key, "'") . "='$value',";
}
$items = rtrim($items, ',');
$sql = "UPDATE " . $table;
$sql .= " SET $items";
$sql .= " WHERE id=" . $id . ";";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro atualizado com sucesso.';
$_SESSION['type'] = 'success';
}
catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
Sorry if it's not right idled.
I put an space on the code after the "FROM" at
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
The error remains the same but know on line 36 that is:
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
Turned the code on line 36 to:
$if (result = $database->query($sql)) {
The error disappeared, others problems not relative to this question happened.

Just in case this question isn't closed as off-topic -> typo generated, I'd better provide an acceptable answer.
Add a space between FROM and $table in your SELECT query.
Check for a non-false result from your query.
Your new code could look like this:
$sql = "SELECT * FROM `$table`";
if ($id) {
// assuming id has been properly sanitized
$sql .= " WHERE id=$id"; // concatenate with WHERE clause when appropriate
}
if ($result = $database->query($sql)) { // only continue if result isn't false
if ($result->num_rows) { // only continue if one or more row
$found = $result->fetch_all(MYSQLI_ASSOC); // fetch all regardless of 1 or more
}
}
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);"; has too many double quotes in it -- you can tell by how Stack Overflow highlights the characters. I could say that you could clean up the syntax, but it would ultimately be best to scrap your script and implement prepared statements.

Related

wait a few seconds before going further with the function php

so i have this deletefile function and i want it to go back to tyhe home page after 3 seconds automaticly
public function deleteFile($id)
{
try {
$query = "SELECT naam, bestand_path FROM bestanden ";
$query .= "WHERE id='$id'";
$result = $this->datahandler->readsData($query);
$results = $result->fetchAll();
foreach ($results as $row) {
$filename = $row['naam'];
}
$file = getcwd() . "/uploads/" . $filename;
//echo "Absolute Path To Directory is: ";
//echo $delfile;
***if (unlink($file)) {
echo $filename . ' was deleted successfully!';
header('Location: ' . SERVER_URL . '/Home/');***
} else {
echo 'There was a error deleting ' . $filename;
}
$query = "DELETE FROM bestanden ";
$query .= "WHERE id=$id";
$result = $this->datahandler->deleteData($query);
} catch (PDOException $e) {
echo "Fout opgetreden";
}
}
its about the one with the stars around it.
thank you

PHP 7 Warning: Unexpected character in input: '

Every time I run a function in this file, no matter the function even if its just included in another file, the following error keeps popping up, and I can't seem to identify the piece of code that is breaking it.
When I remove a function the same error shows up on a totally different line.
Warning: Unexpected character in input: ' in
Z:\WEB\cgit\functions\tools.php on line 125
<?php
function connect() {
$conn = oci_connect($username, $password, 'localhost:1521/xe');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
} else return $conn;
} //end connect
// /Used to check if a row with the specified value exist in a table
// /INPUT $attribute: index name in $_GET or $_POST
// /INPUT $table: name of table in database
// /INPUT $column: name of column to check against in database
// /INPUT $getOrpost: specifies where the data is stored, options:$_GET or $_POST
function CheckExist($attribute, $table, $column, $getOrpost) {
if (isset($getOrpost)) {
if (!empty($getOrpost) && !empty($getOrpost[$attribute])) {
$input = htmlspecialchars($getOrpost[$attribute]);
$pdo = connect();
$sql = 'SELECT COUNT(' . $column . ') FROM ' . $table . ' where ' . $column . ' = :attribute';
$prepare = oci_parse($pdo, $sql);
oci_bind_by_name($prepare, ':attribute', $input);
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res['COUNT(' . $column . ')'] != 0) {
return true;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
}
}
function CheckExistExt($attribute, $table, $column, $wherecolumn) {
if (isset($attribute)) {
if (!empty($attribute)) {
$input = htmlspecialchars($attribute);
$pdo = connect();
$sql = 'SELECT COUNT(' . $column . ') FROM ' . $table . ' where ' . $wherecolumn . ' = :attribute';
$prepare = oci_parse($pdo, $sql);
oci_bind_by_name($prepare, ':attribute', $input);
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res['COUNT(' . $column . ')'] != 0) {
return true;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
exit();
}
}
}
}
// /Used to return single cell from database
// /INPUT $table: table in the database where to look for the data
// /INPUT $column: the name of the column you want to select
// /INPUT $where_column: the name of the column that contains the data that needs to match the input
// /INPUT $where: the data that will be looked for in the specified column.
function GrabData($table, $column, $where_column, $where) {
$input = $where;
$pdo = connect();
$sql = 'SELECT ' . $column . ' FROM ' . $table . ' where ' . $where_column . ' = :attribute';
$prepare = oci_parse($pdo, $sql);
oci_bind_by_name($prepare, ':attribute', $input);
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res != null) {
return $res;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
// /Used to return the results of a specified mySQL query
// /$query is the basic mySQL query eg: "SELECT * FROM users WHERE email = :email AND password = :password".
// /$bind is a nested array, must be in pairs, eg: 'array(array(':email', 'generic#email.com'), array(':password', 'passwordtext'))'
function GrabMoreData($query, $bind = null) {
$pdo = connect();
$sql = $query;
$prepare = oci_parse($pdo, $sql);
if (!empty($bind)) {
foreach ($bind as $attribute) {
oci_bind_by_name($prepare, $attribute[0], $attribute[1]);
/* echo $attribute[0]." ".$attribute[1];*/
}
}
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res != null) {
return $res;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
function GrabAllData($query, $bind = null) {
$pdo = connect();
$sql = $query;
$prepare = oci_parse($pdo, $sql);
if (!empty($bind)) {
foreach ($bind as $attribute) {
oci_bind_by_name($prepare, $attribute[0], $attribute[1]);
}
}
if (oci_execute($prepare)) {
oci_fetch_all($prepare, $res);
if ($res != null) {
return $res;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
function InsertData($query, $bind = null) {
$pdo = connect();
$sql = $query;
$prepare = oci_parse($pdo, $sql);
if (!empty($bind)) {
foreach ($bind as $attribute) {
oci_bind_by_name($prepare, $attribute[0], $attribute[1]);
}
}
if (oci_execute($prepare)) {
return 'success';
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
?>
I had this problem too and I solved it!
At end of the code after class curly bracket you might be clear surplus lines and PHP ending tag ?>.
<?php
function connect() {
$conn = oci_connect($username, $password, 'localhost:1521/xe');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
} else return $conn;
} //end connect
// /Used to check if a row with the specified value exist in a table
// /INPUT $attribute: index name in $_GET or $_POST
// /INPUT $table: name of table in database
// /INPUT $column: name of column to check against in database
// /INPUT $getOrpost: specifies where the data is stored, options:$_GET or $_POST
function CheckExist($attribute, $table, $column, $getOrpost) {
if (isset($getOrpost)) {
if (!empty($getOrpost) && !empty($getOrpost[$attribute])) {
$input = htmlspecialchars($getOrpost[$attribute]);
$pdo = connect();
$sql = 'SELECT COUNT(' . $column . ') FROM ' . $table . ' where ' . $column . ' = :attribute';
$prepare = oci_parse($pdo, $sql);
oci_bind_by_name($prepare, ':attribute', $input);
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res['COUNT(' . $column . ')'] != 0) {
return true;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
}
}
function CheckExistExt($attribute, $table, $column, $wherecolumn) {
if (isset($attribute)) {
if (!empty($attribute)) {
$input = htmlspecialchars($attribute);
$pdo = connect();
$sql = 'SELECT COUNT(' . $column . ') FROM ' . $table . ' where ' . $wherecolumn . ' = :attribute';
$prepare = oci_parse($pdo, $sql);
oci_bind_by_name($prepare, ':attribute', $input);
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res['COUNT(' . $column . ')'] != 0) {
return true;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
exit();
}
}
}
}
// /Used to return single cell from database
// /INPUT $table: table in the database where to look for the data
// /INPUT $column: the name of the column you want to select
// /INPUT $where_column: the name of the column that contains the data that needs to match the input
// /INPUT $where: the data that will be looked for in the specified column.
function GrabData($table, $column, $where_column, $where) {
$input = $where;
$pdo = connect();
$sql = 'SELECT ' . $column . ' FROM ' . $table . ' where ' . $where_column . ' = :attribute';
$prepare = oci_parse($pdo, $sql);
oci_bind_by_name($prepare, ':attribute', $input);
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res != null) {
return $res;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
// /Used to return the results of a specified mySQL query
// /$query is the basic mySQL query eg: "SELECT * FROM users WHERE email = :email AND password = :password".
// /$bind is a nested array, must be in pairs, eg: 'array(array(':email', 'generic#email.com'), array(':password', 'passwordtext'))'
function GrabMoreData($query, $bind = null) {
$pdo = connect();
$sql = $query;
$prepare = oci_parse($pdo, $sql);
if (!empty($bind)) {
foreach ($bind as $attribute) {
oci_bind_by_name($prepare, $attribute[0], $attribute[1]);
/* echo $attribute[0]." ".$attribute[1];*/
}
}
if (oci_execute($prepare)) {
$res = oci_fetch_array($prepare, OCI_ASSOC + OCI_RETURN_NULLS);
if ($res != null) {
return $res;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
function GrabAllData($query, $bind = null) {
$pdo = connect();
$sql = $query;
$prepare = oci_parse($pdo, $sql);
if (!empty($bind)) {
foreach ($bind as $attribute) {
oci_bind_by_name($prepare, $attribute[0], $attribute[1]);
}
}
if (oci_execute($prepare)) {
oci_fetch_all($prepare, $res);
if ($res != null) {
return $res;
} else {
return false;
}
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}
function InsertData($query, $bind = null) {
$pdo = connect();
$sql = $query;
$prepare = oci_parse($pdo, $sql);
if (!empty($bind)) {
foreach ($bind as $attribute) {
oci_bind_by_name($prepare, $attribute[0], $attribute[1]);
}
}
if (oci_execute($prepare)) {
return 'success';
} else {
$e = oci_error($prepare);
echo $e['message'];
}
}

how to check success on insert using OCI

I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

How to run MySQL query with transaction in Zend Framework 2

I have zf2 model. Inside the model, there is a function to communicate with the database with transaction.
Between the transaction I'm calling a recursive function to do transaction, where I'm passing the transaction object. Without recursive function calling it's running fine, but when I'm going to call any function where some query is running, it sends false, and due to receiving false it's being rollbacked. Below are the example code:
<?php
namespace Admin\Model;
use Zend\Db\TableGateway\TableGateway;
use Exception;
class ProjectAssignTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* $empidArray = array(1, 2, 3, 5, 12, 35);
*/
public function saveProjectAssignment($project_id, $empidArray, $data) {
$connection = $this->tableGateway->getAdapter()->getDriver()->getConnection();
$connection->beginTransaction();
try {
$sqlDelete = "DELETE FROM rjs_assignproject WHERE project_id= '" . $project_id . "' ";
$connection->execute($sqlDelete);
for ($x = 0; $x < count($empidArray); $x++) {
$sqlInsert = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $empidArray[$x] . "',designation_id='" . $data['desgi_' . $empidArray[$x]] . "',comment='" . $data['comment_' . $empidArray[$x]] . "',datetime_from='" . $data['time_from' . $empidArray[$x]] . "',datetime_to='" . $data['time_to' . $empidArray[$x]] . "' ";
$resultHistory = $connection->execute($sqlInsert);
if (!$this->recursiveEntry($connection, $empidArray[$x], $project_id)) {
throw new Exception();
} else {
return true;
}
}
$connection->commit();
return true;
} catch (Exception $ex) {
$connection->rollback();
}
}
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true;
}
}
}
} catch (Exception $ex) {
return false;
}
}
}
Your method doesn't return anything after try/catch block:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
// ...
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true; // We will never get here
}
} catch (Exception $ex) {
return false;
}
// return null
}
Try this:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
}
}
}
} catch (Exception $ex) {
return false;
}
return true;
}

Mysqli Class Always returns NULL for results with one var passed through

Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$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;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }

Categories