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'];
}
}
Related
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
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.
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);
}
Currently I use MySQLi and I try to convert all my MySQLi to PDO.
In MySQLi I have this code and it work very fine:
// connection string in MySQLi
if ($query = $connection->prepare("SELECT u.ID as ID,
u.Username as Username,
u.Firstname as Firstname,
u.Lastname as Lastname,
// ... many more
FROM Users u
INNER JOIN Gender g ON u.Gender = g.id
// ... many more
WHERE u.ID = ?")) {
$query->bind_param('s', $_SESSION['ID']);
$query->execute();
$metaResults = $query->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams = '';
foreach ($fields as $field) {
if (empty($statementParams)) {
$statementParams.="\$column['" . $field->name . "']";
} else {
$statementParams.=", \$column['" . $field->name . "']";
}
}
$statment = "\$query->bind_result($statementParams);";
eval($statment);
$query->store_result();
$affected = $query->num_rows;
// this request return me only ONE row
if ($affected == 1) {
while ($query->fetch()) {
foreach ($column as $key => $value) {
if ($key == "lookingFor") {
$row_tmb[$key] = formatLookingFor($value, $language, "");
} else {
$row_tmb[$key] = utf8_encode($value);
$row_tmb[$key] = $value;
}
}
$results[] = $row_tmb;
}
$query->free_result();
$query->close();
$profileData = $results[0];
// ... other code
}
This is return to my all column names and all 1 data row and I'm verry happy. So, I try to convert this code into PDO with new PDO code:
// good connection string without error in PDO code and the same query as you see up.
if ($query = $connection->prepare($sql)) {
$query->execute();
$metaResultsColNumber = $query->columnCount();
for ($i = 0; $i < $metaResultsColNumber; $i++) {
$metaResults[] = $query->getColumnMeta($i, ['name']);
}
var_dump($metaResults);
$fields = $metaResults->fetchColumn();
var_dump($fields);
$statementParams = '';
foreach ($fields as $field) {
if (empty($statementParams)) {
$statementParams.="\$column['" . $field->name . "']";
} else {
$statementParams.=", \$column['" . $field->name . "']";
}
}
$statment = "\$query->bind_result($statementParams);";
eval($statment);
$query->store_result();
$affected = $query->num_rows;
// TRACE
printf("SQL %d row(s) return", $affected);
if ($affected == 1) {
while ($query->fetch()) {
foreach ($column as $key => $value) {
if ($key == "lookingFor") {
$row_tmb[$key] = formatLookingFor($value, $language, "");
} else {
$row_tmb[$key] = utf8_encode($value);
}
}
$results[] = $row_tmb;
}
$query->free_result();
$query->close();
$profileData = $results[0];
And I can't obtain 1) the right column names 2) the data of the returning row
I try to read help into this site and PHP MySQL PDO documentation from many hours.
Do you look for something like that?
//Datastrucure
include("pdo_dbconnect.php");
$stmt = $db->prepare('select * from information_schema.columns where table_name = "' . $_SESSION[$fenster .'_tabelle'] . '" and table_schema = "' .$database.'"');
$stmt->execute();
$f = -1;
while ($data = $stmt->fetch()) {
$f += 1;
//pmsg($data['COLUMN_NAME'] . ' ' .$data['DATA_TYPE'] . ' ' . $data['CHARACTER_MAXIMUM_LENGTH']);
$_SESSION['_fieldName'][$f] = $data['COLUMN_NAME'];
$_SESSION['_fieldLenght'][$f] = $data['CHARACTER_MAXIMUM_LENGTH'];
$_SESSION['_extra'][$f] = $data['EXTRA'];
}
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 */ }