Codeigniter this->db->query unidentified index - php

I am trying to execute the following query using CodeIgniter, but I am getting
Unidentified index for ->row['code'];
public function getSExtension($id) {
$temp = array();
$query = $this->db->query("SELECT extension_id FROM " . DB_PREFIX . "zipcode_shipping WHERE `zip_code` = '" . $id . "'");
if($query->num_rows) {
foreach ($query->rows as $key => $value) {
$code = $this->db->query("SELECT code FROM " . DB_PREFIX . "extension WHERE `extension_id` = '" . $value['extension_id'] . "'")->row['code'];
$this->language->load("shipping/".$code);
$temp[] = $this->language->get('text_title');
}
}
return $temp;
}

The problem is you have not correctly retrieved a result set which requires a method call. As you have it you are trying to use db properties that don't exist i.e. $query->rows should probably be $query->row_array().
Documentation Here.
In the example below I use result() and row() instead of any "array" methods.
Try this.
$temp = array();
$query = $this->db->query("SELECT extension_id FROM ".DB_PREFIX."zipcode_shipping WHERE `zip_code` = '".$id."'");
if($query->num_rows() > 0)
{
foreach($query->result() as $value)
{
$code = $this->db->query("SELECT code FROM ".DB_PREFIX."extension WHERE `extension_id` = '".$value->extension_id."'")->row()->code;
$this->language->load("shipping/".$code);
$temp[] = $this->language->get('text_title');
}
}

Related

To create random first and last name. multiple pieces

I want to create a script. The script will automatically list random firstname and lastname.
There are two database tables.
First: fake_name_id, fake_firstname
Second:fake_name_id,fake_lastname
So far I have made this:
controller file
$data['lastname'] = array();
$results = $this->getRandomLastNames();
foreach ($results as $result) {
$data['lastname'][] = array(
'lastname' => $result['lastname'],
);
}
$data['fullnames'] = array();
$results = $this->getRandomNames();
foreach ($results as $result) {
$data['fullnames'][] = array(
'firstname' => $result['firstname'],
);
}
model file >>>>> sql query firstname and lastname
public function getRandomName($fake_name_id) {
$query = $this->db->query("SELECT DISTINCT *, fake_firstname FROM " . DB_PREFIX . " fakereviews_name WHERE fake_name_id = '" . (int)$fake_name_id . "'");
if ($query->num_rows) {
return array(
'fake_name_id' => $query->row['fake_name_id'],
'firstname' => $query->row['fake_firstname'],
);
} else {
return false;
}
}
public function getRandomNames($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_name ORDER BY Rand() ASC LIMIT 0, 20";
$fake_firstname_data = array();
$query = $this->db->query($sql);
foreach ($query->rows as $result) {
$fake_firstname_data[$result['fake_name_id']] = $this->getRandomName($result['fake_name_id']);
}
return $fake_firstname_data;
}
public function getRandomLastName($fake_name_id) {
$query = $this->db->query("SELECT DISTINCT *, fake_lastname FROM " . DB_PREFIX . " fakereviews_lastname WHERE fake_name_id = '" . (int)$fake_name_id . "'");
if ($query->num_rows) {
return array(
'fake_name_id' => $query->row['fake_name_id'],
'lastname' => $query->row['fake_lastname'],
);
} else {
return false;
}
}
public function getRandomLastNames($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_lastname ORDER BY Rand() ASC LIMIT 0, 20";
$fake_lastname_data = array();
$query = $this->db->query($sql);
foreach ($query->rows as $result) {
$fake_lastname_data[$result['fake_name_id']] = $this->getRandomLastName($result['fake_name_id']);
}
return $fake_lastname_data;
}
twig file
{% for fullname in fullnames %}
{{ fullname['firstname'] }} {{ fullname['lastname'] }}
{% endfor %}
When the page loads. well creates 20 pieces of firstname.
But I can't get it to display lastname correctly.
Please help me to create foreach random fullname (first and last name) with predefined quantity.
You can simply use rand() function.
Create an array of fake_firstname and one for fake_lastname and then join them using a loop, wrap everything inside a function and you have what you need.
say you need an array of $n fake names
Example pseudocode:
public function randomNames($n){
// $first_name_array = fetch all first names in an array;
// $last_name_array = fetch all last names in an array;
$random_names = [];
foreach($n as $i){
$random_full_name = $first_name_array[rand(0,$n)%count($first_name_array)].' '.$last_name_array[rand(0,$n)%count($last_name_array)];
array_push($random_names,$random_full_name);
}
return($random_names);
}

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

Get Categories (multiple levels)

I am making a script which will load all categories from a database. I just don't know how I can do this in a way which is shorter.
I am trying to figure out a way in which I can theoretically load infinite levels of categories.
$stmt1 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row1 = $db->fetch($stmt1))
{
$stmt2 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row1['Rubrieknummer'] . "'");
while($row2 = $db->fetch($stmt2))
{
$stmt3 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row2['Rubrieknummer'] . "'");
while($row3 = $db->fetch($stmt3))
{
$stmt4 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row3['Rubrieknummer'] . "'");
while($row4 = $db->fetch($stmt4))
{
$row3['CATEGORY3'][] = array(
'CATEGORY4_NAME' => ucfirst(strtolower($row4['Rubrieknaam'])),
);
}
$row2['CATEGORY3'][] = array(
'CATEGORY3_NAME' => ucfirst(strtolower($row3['Rubrieknaam'])),
'CATEGORY4' => $row2['CATEGORY4'],
);
}
$row1['CATEGORY2'][] = array(
'CATEGORY2_NAME' => ucfirst(strtolower($row2['Rubrieknaam'])),
'CATEGORY3' => $row2['CATEGORY3'],
);
}
$catagories[] = array(
'CATEGORY_NAME' => ucfirst(strtolower($row1['Rubrieknaam'])),
'CATEGORY2' => $row1['CATEGORY2'],
);
}
I would like to have some ideas on how to make this happen.
(I am using a little template system that processes the array that is being made)
EDIT:
Thanks to Ivijan Stefan Stipić I was able to solve this.
This is what I ended up doing
$categories = build_category(0);
And the function:
function build_category($parent, $row = NULL)
{
global $db;
// Initialise array
$data = array();
// Basic SQL statement
$sql = "SELECT * FROM Rubriek";
// Where condition based on $row
if(is_null($row))
{
$where = " WHERE Hoofdrubriek IS NULL";
}
else
{
$where = " WHERE Hoofdrubriek = '" . $row['Rubrieknummer'] . "'";
}
// Execute query
$stmt = $db->query($sql . $where);
// Next level parent
$next = $parent + 1;
// Fetch results
while($row = $db->fetch($stmt))
{
$data[] = array(
'CATEGORY' . $parent . '_NAME' => ucfirst(strtolower($row['Rubrieknaam'])),
'CATEGORY' . $next => build_category($next, $row),
);
}
// Return data
return $data;
}
What do you think about this solution?
function next_level($val)
{
global $db;
$stmt = $db->query("SELECT * FROM Rubriek WHERE Rubrieknummer != '" .$val. "' AND Hoofdrubriek = '" .$val. "'");
while($row = $db->fetch($stmt))
{
echo ucfirst(strtolower($row['Rubrieknaam']));
echo next_level($row['Rubrieknummer']);
}
}
$stmt = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row = $db->fetch($stmt))
{
echo ucfirst(strtolower($row['Rubrieknaam']));
echo next_level($row['Rubrieknummer']);
}
If I understand correctly this is the number of categories with unlimited subcategories.

creating a function to do standard DELETEs using prepared statments and php

I am currently going through a nettuts.com tutorial on building a twitter clone and there they have a function for deleting rows from a database and they are using the query method but i tried converting the function to a prepared statement.However I get the Invalid parameter number: parameter was not defined error.Here is the code for the function
public function delete($table, $arr){
$query = "DELETE FROM " . $table;
$pref = "WHERE ";
foreach ($arr as $key => $value) {
$query .= $pref. $key . " = " . ":" . $key;
$pref = "AND ";
}
$query .= ";";
$result = $this->db->prepare($query);
$result->execute($arr);
}
$connect = new Model();
$connect->delete("ribbits", array("user_id" => 2,
"ribbit" => "trial ribbit"
));
can someone please tell me what I am doing wrong?Thank you!
When you pass your array to ->execute(), the keys need to have the : character before them (just like they appear in the SQL query).
So, in your delete function, build the SQL query like this:
public function delete($table, $arr){
$keys = array();
$values = array();
foreach($arr as $key => $value){
$keys[] = $key . " = :" . $key;
$values[":".$key] = $value;
}
$query = "DELETE FROM " . $table . " WHERE " . implode(" AND ", $keys);
$result = $this->db->prepare($query);
$result->execute($values);
}

PHP make Array from MYSQL

i working on Authorize.net gateway i need to create below array for itemized bill
$sql= "select * from shop where cusid = '1'";
$sqlexc= mysql_query($sql) or die(mysql_error());
$line_items = array();
while ($title = mysql_fetch_array($sqlexc)) {
$line_items[] = ('Coupon',' $title[6]', '1', '0.99', 'Y');
}
how to create below kind of array
/* $line_items = array(
"Coupon1','description','2','10.99','Y'",
"Coupon2','description','2','10.99','Y'",
"Coupon3','description','2','10.99','Y'",);*/
uh.. if you want it to be exactly the same...
$i=0;
$line_items = array();
while ($title = mysql_fetch_array($sqlexc)) {
$line_items[] = "Coupon" . ++$i . "', '" . $title[6] . "', '2', '10.99', 'Y'";
}
However I would use mysql_fetch_assoc over mysql_fetch_array (actually I would switch to PDO as mysql is deprecated)
$line_items = array();
while ($title = mysql_fetch_array($sqlexc)) {
$line_items[] = $title;
}
foreach ($line_items as $row){
echo $row[0]." ".$row[1]." ".$row[2]." ".$row[3]."<br>";
}

Categories