How to use getColumnMeta? - php

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

Related

Laravel dynamic keys and values query writing

i want to write this query in laravel can anyone please help me please. i am new to laravel.
public function selectTableData($table,$condition)
{
try{
$query = "SELECT * from ".$table;
if(is_array($condition))
{
$query .= " WHERE ";
foreach ($condition as $key => $value)
$query .= $key . "= '".$value."' AND ";
$query = rtrim($query,'AND ');
}
$result = mysql_query($query);
if (!$result)
throw new Exception(mysql_error());
if (mysql_num_rows($result) > 0) {
return mysql_fetch_assoc($result);
}
else
return false;
} catch ( Exception $e ) {
throw new Exception($e->getMessage ());
}
}
And this aswell, i want to write this code in laravel query format
public function insertTableData($table,$data)
{
try{
// generate insert query
if(is_array($data)){
$query = 'INSERT INTO '. $table.' ( ';
foreach ($data as $key => $value)
$query .= $key . ',';
$query = rtrim($query,',');
$query .= ') VALUES (';
foreach ($data as $key => $value)
$query .= '"'.$value.'",';
$query = rtrim($query,',');
$query .= ')';
$result = mysql_query($query);
//if (!$result) {
// throw new Exception( 'Could not run query: ' . mysql_error());
//}
return $result;
}
else
return false;
} catch ( Exception $e ) {
throw new Exception($e->getMessage ());
}
}
if it is in capsule format then it wil be good
You can write this query in laravel like below.
$query = DB::table($table);
if(is_array($condition)) {
foreach ($condition as $key => $value) {
$query->where($key, "'" . $value . "'");
}
}
$result = $query->get();
if (count($result) > 0) {
return $result;
} else {
return false;
}
Let me assume that your eloquent model class is SomeModel. Then You could try like the following for first query/method-
$query = new SomeModel();
if(is_array($condition))
{
foreach ($condition as $key => $value)
$query = $query->where($key, $value);
}
$result = $query->get();
And for the second-
if(is_array($data)){
$query = new SomeModel();
foreach ($data as $key => $value)
$query->$key = $value;
$query->save();
}
Hope it solves your problem :)

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

Copying Row, Losing NULL value

I have this working where it will copy the row, and then link the new row to the previous row.
Where my issue is, is in copying over the NULL values. When I run this all null values go into the new row as blank.
How would I get it to change the value to NULL if it was originally NULL?
$result = $mysqli->query("SELECT * FROM rdpricing WHERE psid = '$dupsid';");
if($result->num_rows >= "1"){
$count = $result->num_rows;
$cols = array();
$result = $mysqli->query("SHOW COLUMNS FROM rdpricing");
while ($r = $result->fetch_array(MYSQLI_ASSOC)) {
if (!in_array($r["Field"], array("rdpid", "psid", "rdold"))) { //Excluding these columns
$cols[] = $r["Field"];
}
}
// Build and do the insert
$result = $mysqli->query("SELECT * FROM rdpricing WHERE psid = '$dupsid';");
while ($r = $result->fetch_array(MYSQLI_ASSOC)) {
$insertSQL = "INSERT INTO rdpricing (" . implode(", ",$cols) . ", rdold) VALUES (";
$count = count($cols);
foreach($cols as $counter=>$col) {
**// This is where I Believe it needs to happen, and what I have attempted, and it is NOT working**
if(empty($r[$col]) || is_null($r[$col]) || $r[$col] == ""){
$r[$col] = NULL;
}
$insertSQL .= "'" . $mysqli->real_escape_string($r[$col]) . "'";
if ($counter < ($count - 1)) {
$insertSQL .= ", ";
}
} // END foreach
$insertSQL .= ", '".$r["rdpid"]."');";
$mysqli->query($insertSQL);
if ($mysqli->affected_rows < 1) {
printf("%s\n", $mysqli->error);
} else {
}
$new_id = $mysqli->insert_id;
$statement = $mysqli->prepare("UPDATE rdpricing SET `psid`=? WHERE `rdpid`=?");
$statement->bind_param('ss', $new_psid, $new_id);
// Execute the prepared query.
$statement->execute();
$statement->close();
}
}
Generated from info in the comments:
#reset/create before the foreach, create an empty array
$insertSQLValues=array();
#in the foreach do some on given type
if(is_null($r[$col])){#real null
$r[$col] = "null";
} else if (empty($r[$col]) || $r[$col] == ""){#empty values
$r[$col] = "''";
} else {#standart data
$r[$col] = "'".$mysqli->real_escape_string($r[$col])."'";
}
$insertSQLValues[]=$r[$col];
#later
$insertSQL .= implode(', ',$insertSQLValues).", '".$r["rdpid"]."');";
Hopefully you can merge that into your code.

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

implode to fix update sql

I have this function
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'
The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.
Yes,
$sql = substr($sql,'',-1);
I would use
$sql = rtrim($sql, ',');
Either that or instead of appending to a string, append to an array and use implode.
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);

Categories