I have following data array returned by Item_model. This array included some values of MySQL tables columns such as 'r_qty' and 'ap_qty'.
$this->data['issueData']=$this->Item_model->ItemRequestfromHDData($id);
Item_model
function ItemRequestfromHDData($id)
{
$this->db->select('store_update_stock.*,store_update_stock_details.*,tbl_user.username,store_item.*,
sum(qty) as avqty, sum(store_update_stock_details.r_qty) as r_qty,
sum(store_update_stock_details.ap_qty) as ap_qty');
$this->db->from('store_update_stock_details');
$this->db->join('store_update_stock', 'store_update_stock.update_stock_id=store_update_stock_details.update_stock_id');
$this->db->join('tbl_user', 'store_update_stock.supplier=tbl_user.userId');
$this->db->join('store_item', 'store_update_stock_details.item=store_item.item_id', 'left');
$this->db->where(array('store_update_stock.update_stock_id' => $id, 'store_update_stock_details.status' => 1));
$this->db->group_by('store_item.item_id');
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
I want to assign these two columns / values to variables. I tried following assignments.
$r_qty = $data['r_qty'];
$ap_qty = $data['ap_qty'];
but didn't get the expected result. What may be going wrong ? Can anyone help ?
As per codeigniter documentation,
result()
This method returns the query result as an array of objects, or an
empty array on failure.
Typically you’ll use this in a foreach loop, like this:
$query = $this->db->query("YOUR Q enter code here QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
So, your code should be
foreach ($this->data['issueData'] as $data)
{
$r_qty = $data->r_qty;
$ap_qty = $data->ap_qty;
}
Related
So I was experimenting with PDO queries. Take a look at this snippet:
1. $rows = $stmt->fetchColumn();
2. echo $rows;
3. $row = $stmt->fetch();
4. print_r($row);
This is just an observation... not sure how true tho!
Line 2 is executed and returns the number of rows (in my case 1 because I was just authenticating a user).
Line 4 doesn't return anything.
If you flipped the order:
1. $row = $stmt->fetch();
2. print_r($row);
3. $rows = $stmt->fetchColumn();
4. echo $rows;
The array from line 2 is printed but line 4 returns nothing! Is this proper behavior?
Anyways, how do I achieve the following result?
if ($stmt->fetchColumn() == 1) {
$row = $stmt->fetch();
print_r($row);
} else {
echo '<div class="error-message">Verify Your Credentials</div>';
}
It is proper behavior, fetchColumn fetches one column. You cant fetch it twice. You can use:
/* fetches row from the result, if theres no row in the result, fetch returns false */
$row = $stmt->fetch();
/* compare if $row is true (in PHP, "boolean value" of unempty array is true) */
if ( $row ) {
print_r($row);
} else {
echo '<div class="error-message">Verify Your Credentials</div>';
}
this answer might help you PDO fetch one column from table into 1-dimensional array
fetchColumn only returns a single result but you can flatten your result in different ways using the pdo::fetch methods, you should look them up and they will quickly and simply sort out your results. Try this for some more reading also https://phpdelusions.net/pdo/fetch_modes
Good morning,
I have a problem with mysql and coeigniter 3.
if I request data with
$ query = $ this-> db-> query ($ queri_str);
it does not give me results.
if I enter the query on phpmyadmin it shows me two results.
$ queri_str = 'SELECT * FROM `my_table` WHERE` id_mytable2` = "'. $ id_name. '"';
The database tables were created with mysql workbench and automatically the reference to the main table with a 1: n ratio was added
Try this query
$this->db->select('*');
$this->db->where('id', '58e5j0m5bqrs7hk8suokko28hj7ni0v6');
$result = $this->db->get('ci_sessions')->result_array();
print_r($result);
Try this solution, you want to do a normal select,I don't know the query your wrote but
public fucntion get_data($id){
$this->db->select('*');
$this->db->from('your_table');
$this->db->where('id','=' ,'$id');
$query = $this->db->get();
$data = $query->result_array();
return $data;
}
the problem is back.
I'll explain.
function myfunction($id_myname) {
$this->db->select('*');
$this->db->where('id_myname', $id_myname);
//$query = $this->db->get('my_table');
$query = $this->db->get('my_table');
//print_r($query);
//var_dump($query);
if ( !$query ){
$error = $this->db->error(); // Has keys 'code' and 'message'
}
return $query->result();
}
when I call this function an empty value comes back to me.
While if I enter the value of the query in phpmyadmin I find two values
I have a function which is printed below. THis is meant to dynamicly draw user data from the database using PDO (that situation is clear and all works well). But, instead of returning the result (i e. an email for you("email)), it returns the number 1.
Here's my setup:
public function you($row) {
if(isset($_COOKIE["SK"])) {
$pw = $this->baseXencode($_SESSION["password"]);
$usr = $this->baseXencode($_SESSION["username"]);
$q = "SELECT $row FROM SN_users WHERE username=':USR' AND password=':PW'";
$this->netCore->q($q);
$this->netCore->bind(":PW", $pw);
$this->netCore->bind(":USR", $usr);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
} else {
$q = "SELECT $row FROM SN_users WHERE username='Anonymous' AND password='Anonymous'";
$this->netCore->q($q);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
}
}
}
$this->netCore->q() = PDO query
$this->netCore->single() PDO fetch(PDO::FETCH_ASSOC)
As for ->bind, self-explanatory.
Please help, will be very much appreciated.^^
When using parametrized queries, you don't put the parameters in quotes. That prevents the parameters from being substituted, since it's treated as a literal string. So it should be:
$q = "SELECT $row FROM SN_users WHERE username=:USR AND password=:PW";
I'm surprised it's returning 1. I'd expect your code to cause an error, because single() should be returning false, and false[$row] is not valid.
You should also check that a row was returned; if the username and password are not valid, you won't get an result. So it should be:
$result = $this->netCore->single();
if ($result) {
return $result[$row];
} else {
return false;
}
And the caller of you() needs to check the value as well.
Based on this question How to insert array into mysql using PDO and bindParam?
I'm trying to insert values of an array into mysql via PDO.
I'm having a hard time of it, because I keep getting the following error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
for this line $stmt->execute();
I'm guessing the problem has something to do with this line
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR); Specifically 'val$count', but I'm not sure exactly what is going wrong.
QUESTION: What am I doing wrong? How can I fix this?
Anyway here is the code I'm using along with the sample array.
$lastInsertValue=87;
$qid[0][0]=1;
$qid[0][1]=1;
$qid[1][0]=2;
$qid[1][1]="null";
$qid[2][0]=3;
$qid[2][1]=0;
$array_count = count($qid);
if (isset($lastInsertValue))
{
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
$a=0;
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2)";
$count = 0;
$stmt = $dbh->prepare($sql);
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
$stmt->execute();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Yikes, so many issues.
Your array building is so verbose. Try this
$stqid = array();
foreach ($qid as $qidArr) {
$stqid[] = $lastInsertValue; // no idea why you repeat this
$stqid[] = $qidArr[0];
$stqid[] = $qidArr[1];
}
Use positional placeholders if you're simply relying on number of arguments
$sql = 'INSERT INTO ... VALUES (?, ?, ?)';
bindParam uses references which you are overwriting with each loop iteration. You would want to use bindValue() instead
Your query only has 3 placeholders but your $stqid array has 9 items. This is the source of your error.
You have single quotes around a variable, which will be treated as the variable name $count (not the value), try concatenating the variable to the string. Give this a try:
$stmt->bindParam(':val' . $count, $val,PDO::PARAM_STR);
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
so in case $i = 2, it will add $stqid[6], $stqid[7], $stqid[8] so
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
will give you :val0 to :val8
In your query you have only :val0 to :val2.
Also having multiple values in one field in database is bad. Don't do it. Try to redesign your DB differently
EDIT: bad math in the morning... sorry
How can I return a value of 'no data found' if my query returns no results???
This is my code:
function getTerms($letter) {
$this->db->select('term, definition');
$this->db->from('glossary');
$this->db->where(array('letter' => $letter));
$query = $this->db->get();
foreach ($query->result() as $row) {
$data[] = array(
'term' => $row->term,
'definition' => $row->definition
);
}
return $data;
}
It currently returns the $data variable even if the query returns no results which is giving me php errors. How can I check that there are results before returning the $data array.
Simply check that the query returns at least one row:
if ($query->num_rows() > 0) {
// query returned results
} else {
// query returned no results
}
Read more in the docs
It currently returns the $data variable even if the query returns no results which is giving me php errors.
It's a good habit to initialize the array that you intend to build:
$data = array();
// Loop through possible results, adding to $data
If there are no results you'll get an empty array returned, then check that in your controller.
This way, at least the variable is defined and you won't get notices.
What about to give initial empty array value for $data
Just put
$data = array();
before foreach
<?php
return is_array($data) ? $data : array();
}