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 :)
Related
I am new to PDO PHP. I have created a post data function in order to achieve the insertion functionality. Here is my code.
public function PostData($conn, $table, $data)
{
try {
$query = "INSERT INTO " . $table . "(";
$arraylen = count($data);
$keyloopcount = 0;
foreach ($data as $key => $values) {
$query .= $key;
if ($keyloopcount != $arraylen - 1) {
$query .= ",";
}
$keyloopcount++;
}
$valloopcount = 0;
$query .= ") VALUES (";
foreach ($data as $key => $values) {
$query .= "':" . $key . "'";
if ($valloopcount != $arraylen - 1) {
$query .= ",";
}
$valloopcount++;
}
$query .= ")";
$stmt = $conn->prepare($query);
foreach ($data as $key => &$values) {
$stmt->bindParam(':'.$key, $values, PDO::PARAM_STR);
}
if ($stmt->execute()) {
$stmt->debugDumpParams();
echo "me";
} else {
echo "die";
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
When I execute this query. It doesn't show any exceptions. but when I look into my Database. It shows inserted records as follows.
I am wondering if there is a way I can debug what are the values in the binded params. I have also looked for $stmt->debugDumpParams(); as shown in the code. But it doesn't shows the values of params.
Need Guidance. TIA.
I sorted it out. I was making a silly mistake. The solution was so simple and easy.
Solution
The problem was lying in the part of the code.
foreach ($data as $key => $values) {
$query .= "':" . $key . "'";
if ($valloopcount != $arraylen - 1) {
$query .= ",";
}
$valloopcount++;
}
Changed the code to:
foreach ($data as $key => $values) {
$query .= ":" . $key;
if ($valloopcount != $arraylen - 1) {
$query .= ",";
}
$valloopcount++;
}
Resultant Query Before Amendment:
INSERT INTO cmp_categories(cat_name,cat_slug,cat_desc) VALUES (':cat_name',':cat_slug',':cat_desc')
Resultant Query AfterAmendment:
INSERT INTO cmp_categories(cat_name,cat_slug,cat_desc) VALUES (:cat_name,:cat_slug,:cat_desc)
More Clearly,
Removed ' from VALUES clause. ':cat_desc' => :cat_desc
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'];
}
I'm trying to build my own CMS in classes.
Now I have got a problem when I try to get data from my MySQL database
Instead of one item i'd like to get an collection of all my items
At the end I'd like to get an Object so I can read it out like : $item->id
Here's my code :
static function getContentItems($id, $active, $sort_by, $sort_type, $limit) {
if (isset($id) && !empty($id)) {
$where .= "WHERE id = ".$id;
}
if (isset($active) && !empty($active)) {
$where .= " AND active = ".$active;
}
if (isset($sort_by) && !empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (isset($sort_type) && !empty($sort_type)) {
$where .= " ".$sort_type;
}
}
if (isset($limit) && !empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
if (isset($where) && !empty($where)) {
$query = "SELECT * FROM content ".$where;
} else {
$query = "SELECT * FROM content";
}
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_array($result)) {
$item->id = $data['id'];
}
return $item;
}
}
dont start your $where string with .
if (isset($id) && !empty($id)) {
$where = "WHERE id = ".$id;
}
and alwez print your $query
Better Solution
if (!empty($id) {
$where = " WHERE id = ".$id;
if (!empty($active)) {
$where .= " AND active = ".$active;
if (!empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (!empty($sort_type)) {
$where .= " ".$sort_type;
}
}
}
}
if (empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
and later
$item = new ContentItem();
$data = array(); $i=0;
while ($data = mysql_fetch_object($result)) {
$search_result[$i] = $data;
$i++;
}
return $search_result;
and any id can be retrieve by $search_result[$i]->id
Why don't you use Arrays?
Like this:
$collection = array();
while ($data = mysql_fetch_array($result)) {
$item = new ContentItem();
$item->id = $data['id'];
$collection[] = $item; //Appends the item to the array
}
return $collection;
You can access your array in this way:
$collection = YourClassName::getContentItems(...);
foreach($collection as $item) {
// do something with each $item
print_r($item);
}
Look into using mysql_fetch_object http://php.net/manual/en/function.mysql-fetch-object.php instead of mysql_fetch_array.. it returns rows the db as an object already