How to run MySQL query with transaction in Zend Framework 2 - php

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

Related

How to know the line number from where the exception is coming from in PHP

I am about to finish one project and I noticed that I am getting errors in my error_log file. I have been getting this error when I load my index.php file and in one reload I am getting 21 line lines of the error code.
I have tried debugging from the header.php file. The craziest thing is don't get any error until I load header.php file but when I call header.php in index.php file I get the errors. So I tried to catch the errors by try and catch of from PDO. In the error log file, I am getting error message so I changed my code from this Select Query: ".$e->getMessage() to Select Query: ".$e->getFile() and Select Query: ".$e->getLine(). But, doing this I got line number where the error is getting in not the line it was thrown from.
I think I have a problem in my select query in databse.php. Following is my select query code:
final protected function select($args = array(), $is_die = false){
try {
$this->sql = "SELECT ";
if (isset($args['fields'])) {
if (is_array($args['fields'])) {
$this->sql .= implode(', ', $args['fields']);
} else {
$this->sql .= $args['fields'];
}
} else {
$this->sql .= " * ";
}
$this->sql .= " FROM ";
if (!isset($this->table) || empty($this->table)) {
throw new Exception("Table not set");
}
$this->sql .= $this->table;
/*Join Query*/
if (isset($args['join']) && !empty($args['join'])) {
$this->sql .= " ".$args['join'];
}
/*Join Query*/
if (isset($args['where']) && !empty($args['where'])) {
if (is_array($args['where'])) {
$temp = array();
foreach ($args['where'] as $column_name => $data) {
if (!is_array($data)) {
$data = array(
'value' => $data,
'operator' => '=',
);
}
$str = $column_name.' '.$data['operator'].' :'.str_replace('.', '_', $column_name);
$temp[] = $str;
}
$this->sql .= " WHERE ".implode(' AND ', $temp);
} else {
$this->sql .= " WHERE ".$args['where'];
}
}
/*Group*/
if (isset($args['group_by']) && !empty($args['group_by'])) {
$this->sql .= " GROUP BY ".$args['group_by'];
}
/*Group*/
/*Order*/
if (isset($args['order_by']) && !empty($args['order_by'])) {
$this->sql .= " ORDER BY ".$args['order_by'];
} else {
$this->sql .= " ORDER BY ".$this->table.".id DESC";
}
/*Order*/
/*Limit*/
if (isset($args['limit']) && !empty($args['limit'])) {
if (is_array($args['limit'])) {
$this->sql .= " LIMIT ".$args['limit'][0].",".$args['limit'][1];
} else {
$this->sql .= " LIMIT ".$args['limit'];
}
}
/*Limit*/
$this->stmt = $this->conn->prepare($this->sql);
if (is_array($args['where']) || is_object($args['where'])){
foreach ($args['where'] as $column_name => $data) {
$value = is_array($data) ? $data['value'] : $data; //check if passed where statement was an array, fetch value if so
if (is_int($value)) {
$param = PDO::PARAM_INT;
}elseif (is_bool($value)) {
$param = PDO::PARAM_BOOL;
}elseif (is_null($value)) {
$param = PDO::PARAM_NULL;
}else {
$param = PDO::PARAM_STR;
}
if ($param) {
$this->stmt->bindValue(":".str_replace('.', '_', $column_name), $value, $param);
}
}
}
if ($is_die) {
echo $this->sql;
debugger($this->stmt);
debugger($args, true);
}
$this->stmt->execute();
$data = $this->stmt->fetchAll(PDO::FETCH_OBJ);
return $data;
} catch (PDOException $e) {
error_log(
date('Y-m-d h:i:s A').", Select Query: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
return false;
} catch (Exception $e) {
error_log(
date('Y-m-d h:i:s A').", General: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
return false;
}
}
Is there a possible way to get the line number of a file where the error is thrown form using try catch or any other?
You can use try, catch to get the exception, for the line number use__LINE__
For example
try {
/* Your Code */
} catch (Exception $e) {
echo __LINE__.$e->getMessage() "\n";
}
In your code inside the catch statememt
"Line No : " __LINE__.date('Y-m-d h:i:s A')
For the line no and file path use below
"Line No : " __LINE__." : File Path : ".__FILE__.date('Y-m-d h:i:s A')
I just pasted code to get the line number and function name in my select query.
Following is the code:
Exception("MySQL error $mysqli->error <br> Query:<br> $sql", $msqli->errno);
The select query will look like this after you add the above line of code:
final protected function select($args = array(), $is_die = false){
try {
$this->sql = "SELECT ";
if (isset($args['fields'])) {
if (is_array($args['fields'])) {
$this->sql .= implode(', ', $args['fields']);
} else {
$this->sql .= $args['fields'];
}
} else {
$this->sql .= " * ";
}
$this->sql .= " FROM ";
if (!isset($this->table) || empty($this->table)) {
throw new Exception("Table not set");
}
$this->sql .= $this->table;
/*Join Query*/
if (isset($args['join']) && !empty($args['join'])) {
$this->sql .= " ".$args['join'];
}
/*Join Query*/
if (isset($args['where']) && !empty($args['where'])) {
if (is_array($args['where'])) {
$temp = array();
foreach ($args['where'] as $column_name => $data) {
if (!is_array($data)) {
$data = array(
'value' => $data,
'operator' => '=',
);
}
$str = $column_name.' '.$data['operator'].' :'.str_replace('.', '_', $column_name);
$temp[] = $str;
}
$this->sql .= " WHERE ".implode(' AND ', $temp);
} else {
$this->sql .= " WHERE ".$args['where'];
}
}
/*Group*/
if (isset($args['group_by']) && !empty($args['group_by'])) {
$this->sql .= " GROUP BY ".$args['group_by'];
}
/*Group*/
/*Order*/
if (isset($args['order_by']) && !empty($args['order_by'])) {
$this->sql .= " ORDER BY ".$args['order_by'];
} else {
$this->sql .= " ORDER BY ".$this->table.".id DESC";
}
/*Order*/
/*Limit*/
if (isset($args['limit']) && !empty($args['limit'])) {
if (is_array($args['limit'])) {
$this->sql .= " LIMIT ".$args['limit'][0].",".$args['limit'][1];
} else {
$this->sql .= " LIMIT ".$args['limit'];
}
}
/*Limit*/
$this->stmt = $this->conn->prepare($this->sql);
if (is_array($args['where']) || is_object($args['where'])){
foreach ($args['where'] as $column_name => $data) {
$value = is_array($data) ? $data['value'] : $data; //check if passed where statement was an array, fetch value if so
if (is_int($value)) {
$param = PDO::PARAM_INT;
}elseif (is_bool($value)) {
$param = PDO::PARAM_BOOL;
}elseif (is_null($value)) {
$param = PDO::PARAM_NULL;
}else {
$param = PDO::PARAM_STR;
}
if ($param) {
$this->stmt->bindValue(":".str_replace('.', '_', $column_name), $value, $param);
}
}
}
if ($is_die) {
echo $this->sql;
debugger($this->stmt);
debugger($args, true);
}
$this->stmt->execute();
$data = $this->stmt->fetchAll(PDO::FETCH_OBJ);
return $data;
} catch (PDOException $e) {
error_log(
date('Y-m-d h:i:s A').", Select Query: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
return false;
} catch (Exception $e) {
error_log(
date('Y-m-d h:i:s A').", General: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
Exception("MySQL error $mysqli->error <br> Query:<br> $sql", $msqli->errno);
return false;
}
}
For more information, programmers can visit this link: PHP Manual

PHP mysqli_connect: I'm getting this error when my login page attempt to connect to the database

I'm new to my sqli the improved version of PHP.
<?php
// Class for the transparent access of MySQL
$con = mysqli_connect("host","database","port","user","passwd","conn","querytext","query_id","err","errno","record = array();","row = 0;","rows = 0;") or die ("Some error occured during connection " . mysqli_error($con));
function query($querystring) {
$this->querytext = $querystring;
$this->query_id = mysqli_query($this->querytext, $this->con);
$this->Errno = mysqli_errno($this->conn);
$this->Error = mysqli_error($this->conn);
if($this->query_id) {
if(strtolower(substr(trim($this->querytext),0,6)) == 'select'){
$this->rows = mysqli_num_rows($this->query_id);
} else {
$this->rows = 0;
}
$this->row = 0;
} else {
$this->rows = 0;
$this->row = 0;
$this->halt("Query failed!");
}
}
function setpassword($newpasswd){
$querystring = sprintf("SET PASSWORD = PASSWORD('%s')", $newpasswd1);
return $this->query($querystring);
}
function next_record() {
if($this->row < $this->rows) {
$this->record = mysql_fetch_array($this->query_id);
$this->Errno = mysql_errno($this->conn);
$this->Error = mysql_error($this->conn);
$this->row +=1;
$status = is_array($this->record);
} else {
$status = FALSE;
}
return $status;
}
function seek($pos) {
if(($pos >= 0 && $pos < $this->rows) &&
mysql_data_seek($this->query_id, $pos)) {
$this->Errno = mysql_errno($this->conn);
$this->Error = mysql_error($this->conn);
$this->row = $pos;
}
}
function close() {
$this->query = "";
$this->rows = 0;
$this->row = 0;
mysql_close($this->conn);
}
function htmltable () {
$resulttable='';
if($this->rows > 0){
$resulttable=sprintf("<table %s>", $tableoptions);
while($this->next_record()) {
/* Ueberschriften */
if($this->row == 1) {
$resulttable=$resulttable . "<tr>";
while(list($key, $value)=each($this->record)){
$resulttable=$resulttable . "<th>" . $key . "</th>";
}
$resulttable=$resulttable . "</tr>\n";
reset($this->record);
} /* Ende Ueberschriften */
$resulttable=$resulttable . "<tr>";
while(list($key, $value)=each($this->record)){
$resulttable=$resulttable . "<td>" . $value . "</td>";
}
$resulttable=$resulttable . "</tr>\n";
}
$resulttable=$resulttable . "</table>\n";
}
return $resulttable;
}
?>
You should be connecting to the database using PDO as it is more secure: http://php.net/manual/en/book.pdo.php
These tutorials are pretty good to follow: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://crewow.com/PHP-MySQL-Simple-Select-using-PDO-in-Bootstrap.php
Also, please make sure that your database credentials are in a separate file that gets included into the file you use to connect to the database.

Trying to get property of non-object CRUD

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.

(not all) Data can't reach database

I want to send data to my database (group_id, user_id and group_name) but only the first two are getting into the database. When I var_dump $groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname); it gives me the correct group_name. What am I doing wrong?
When I replace '" . $db->conn->real_escape_string($this->Invitation_group_name) . "' with a random word it is working well..
PHP
$groupinvitation = new GroupInvitation();
if (isset($_POST["Accept"])) {
try {
$group_id = mysql_real_escape_string($_POST["group_id"]);
$groupinfo = $group->GetGroupInfoByGroupId($group_id);
$groupname = $groupinfo['group_name'];
$requestnumber = mysql_real_escape_string($_POST['acceptID']);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$feedback = "Awesome, You just added a friend!";
} catch(Exception $e) {
$feedback = $e -> getMessage();
}
}
DECLARATIONS:
class GroupInvitation
{
private $m_sGroup_invitation_group_name;
public function __set($p_sProperty, $p_vValue)
{
switch($p_sProperty)
{
case "Invitation_group_name":
$this->m_sGroup_invitation_group_name = $p_vValue;
break;
}
}
public function __get($p_sProperty)
{
switch($p_sProperty)
{
case "Invitation_group_name":
return $this->m_sGroup_invitation_group_name ;
break;
}
}
FUNCTION:
public function AddAsGroupMember($number, $group_id)
{
$db = new Db();
$insert = "INSERT INTO tblgroup_member(
group_id,
user_id,
group_name
) VALUES (
'" . $db->conn->real_escape_string($group_id) . "',
'" . $db->conn->real_escape_string($number) . "',
'" . $db->conn->real_escape_string($this->Invitation_group_name) . "'
)";
$db->conn->query($insert);
}
Try changing
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
to
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
You could be setting the property after the insert.

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