Store CI query into an array? - php

I've got the following function in a model, however it keep returning:
Message: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
And I for the life of me can't figure out why.
function getNames() {
$query1 = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer");
$dev = array();
while($row = mysql_fetch_array($query1))
{
$manu = $row['Manufacturer'];
$mod = $row['Model'];
$dev[] = $manu.' '.$mod;
}
return $dev->result();
}
Can anyone help?
Answer for CodeIgniter is:
$query1 = $this->db->query("SELECT * FROM table");
foreach($query1->result_array() as $row)
{
$manu = $row['column1'];
$mod = $row['column2'];
echo $manu.' '.$mod;
}
return $query1->result();

The problem is you're mixing CodeIgniter database methods with built in PHP database methods. mysql_fetch_array expects a resource, not a CI query object.
Check out the docs on fetching results.

Sometimes, when you get a lot of data (lines) to process, you may want to use native php mysql functions like mysql_fetch_array to save memory (for best memory saving I prefer mysql_fetch_row). In this case you can use this :
try {
$query = $this->db->query("SOME QUERY");
while($row = mysql_fetch_row($query->result_id)) {
/* ... */
}
$query->free_result(); //we talked about memory saving right ;-)
} catch(Exception $e) {
/* ... */
}

Related

Prepared Statements in MariDB

I'm fiddling around on my test database, learning how to set it all up.
I'm using PHP and PDO objects to access my database and get Data from it.
I'm also using prepared statements against MySQL Injections.
This is the code I'm using:
mainframe();
function mainframe(){
$connection = establishConnectionToDatabase();
$result = getData($connection);
//var_dump($result);
//echo json_encode($result);
echo $result;
}
function getData($connection){
$fetch = $connection->prepare("SELECT * FROM users_tbl");
$fetch->execute();
$result = $fetch->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
function establishConnectionToDatabase(){
try
{
$connection = new PDO('mysql:host=localhost;dbname=foundationtests',
'verwalter','test');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $connection;
}
The table Im Accessing looks like this (see screenshot):
https://imgur.com/I06RF9e
When executing the above code, I'm only getting back
Notice: Array to string conversion in D:\foundationtests\src\assets\php\test.php on line 12
Array
I already tried out without prepared statements and it worked. I don't know what I'm missing.
You query is fine, you can't echo an array.
As you're returning an array, try this
function getData($connection){
$fetch = $connection->prepare("SELECT * FROM users_tbl");
$fetch->execute();
$result = $fetch->fetchAll(PDO::FETCH_ASSOC);
return (object)$result;
}
This will return your value as an object. Then you can echo whatever value using $result->user_id for example.
You can learn more about objects here
UPDATE
As has been pointed out, you can also just make it return as an object by change the 4th line from $result = $fetch->fetchAll(PDO::FETCH_ASSOC); to $result = $fetch->fetchAll(PDO::FETCH_OBJ);, and then changing the last line back to return $result;

PHP Using a while loop to fetch items, using a dynamic select function?

Okay, I've never ever used dynamic functions, not sure why, I've never liked using explode(), implode(), etc.
but I've tried it out, and something went wrong.
public function fetch($table, array $criteria = null)
{
// The query base
$query = "SELECT * FROM $table";
// Start checking
if ($criteria) {
$query .= ' WHERE ' . implode(' AND ', array_map(function($column) {
return "$column = ?";
}, array_keys($criteria)));
}
$check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
$check->execute(array_values($criteria));
$fetch = $check->fetch(PDO::FETCH_ASSOC);
return $fetch;
}
This is my query.
Basically I will return the variable $fetch which holds the fetch method.
and then somewhere, where I want to use the while loop to fetch data, I will use that:
$r = new Database();
while ($row = $r->fetch("argonite_servers", array("server_map" => "Wilderness")))
{
echo $row['server_map'];
}
Now, I am not getting any errors, but the browser is loading and loading forever, and eventually will get stuck due to lack of memory.
That's because the loop is running and running without stopping.
Why is it doing this? How can I get this dynamic query to work?
EDIT:
$r = new Database();
$q = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo $row['server_map'];
}
One nice feature of PDO is that the PDOStatement implements the Traversable. This means you can iterate it directly:
// `$check` is a `PDOStatement` object
$check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
$check->execute(array_values($criteria));
$check->setFetchMode(PDO::FETCH_ASSOC);
return $check;
Use it:
$statement = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));
foreach ($statement as $row) {
}
this is because you call your fetch function in a loop and it re-starts the query every time. You need to call the $check->fetch() in loop instead.
or in other words, if your fetch function (which should probably have a different name) would return $check, then on the returned object you should call fetch() in a loop:
$r = new Database();
$q = $r->fetch(...);
while($q->fetch()){...}
you also need to edit your fetch function to end like this:
$check->execute(array_values($criteria));
return $check;
}

Mysql result as array

I have a php function that interogates a table and gets all the fields in a column if a condition is fulfield. So the function returns a collection of elements.
The problem is that i want this function to return an array that i can parse and display.
The code below:
function get_approved_pictures(){
$con = mysql_connect("localhost","valentinesapp","fBsKAd8RXrfQvBcn");
if (!$con)
{
echo 'eroare de conexiune';
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mynameisbrand_valentineapp", $con);
$all = (mysql_query("SELECT picture FROM users WHERE approved = 1"));
$row=mysql_fetch_assoc($all);
// mysql_close($con);
return $row['picture'];
}
Where am I wrong?
You need to use the loop for traversing all the data fetched by the query:
$pictures=array();
while($row=mysql_fetch_assoc($all))
{
$pictures[]=$row['picture'];
}
return $pictures;
Do it like this
$all = mysql_query("SELECT picture FROM users WHERE approved = 1");
$arr = array(); // Array to hold the datas
while($row = mysql_fetch_array($all)) {
$data = $row['picture'];
array_push($arr,$data);
}
return $arr;
You can now insert it into a function and return the values.
Note : mysql_* functions are being depreciated. Try to avoid them.
For the sake of diversity and to give you some sense of how to use PDO instead of deprecated mysql_*, this is how your function might look like:
function get_approved_pictures(){
$db = new PDO('mysql:host=localhost;dbname=mynameisbrand_valentineapp;charset=UTF-8',
'valentinesapp', 'password');
$query = $db->prepare("SELECT picture FROM users WHERE approved = 1");
$query->execute();
$pictures = $query->fetchAll(PDO::FETCH_ASSOC);
$db = null;
return $pictures;
}
Disclaimer: all error handling intentionally omitted for brevity
For the sake of diversity and to give you some sense of how the things have to be instead of inconvenient and wordy PDO, this is how your function might look like:
function get_approved_pictures(){
global $db;
return $db->getCol("SELECT picture FROM users WHERE approved = 1");
}
Disclaimer: all error handling is up and running but intentionally encapsulated into private methods for invisibility.

how to fetch all the row of the result in php mysql?

In my table I have 2 records with companyid = 1 , but when I run the php below for companyid = 1 it returns only the first one !
How can I fetch all the records?
The php file:
if (isset($_GET["companyid"])) {
$companyid = $_GET['companyid'];
// get a product from products table
$result = mysql_query("SELECT * FROM `products`
WHERE companyid = $companyid;");
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)){
$product = array();
$product["pid"] = $row["pid"];
$product["productname"] = $row["productname"];
}
$response["product"] = array();
array_push($response["product"], $product);
// success
$response["success"] = 1;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no product JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
Using mysql_fetch_array is happening the same.
it returns {"product":[{"pid":"12371","productname":"test"}],"success":1}
when i run a query without parameters select * from table using mysql_fetch_array it returns all the rows ..
As NikiC pointed out you should not be using the mysql_ functions any longer, you can fetch the entire array in both PDO and mysqli, Here is a example to fetch all rows using the mysqli->fetch_all function, hope this helps!
//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
php.net/mysql_fetch_assoc
I would recommend you to use PDO instead of mysql_
if (!empty($result)) {
Could be is_resource($result)
You need to loop through the result to pull all the rows:
while($row = mysql_fetch_assoc($result)){
//Do stuff
}
On a side note, you should be using at least mysqli or PDO instead of mysql_* functions.
I strongly believe the batch processing with Doctrine or any kind of iterations with MySQL (PDO or mysqli) are just an illusion.
#dimitri-k provided a nice explanation especially about unit of work. The problem is the miss leading: "$query->iterate()" which doesn't really iterate over the data source. It's just an \Traversable wrapper around already fully fetched data source.
An example demonstrating that even removing Doctrine abstraction layer completely from the picture, we will still run into memory issues:
echo 'Starting with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";
$pdo = new \PDO("mysql:dbname=DBNAME;host=HOST", "USER", "PW");
$stmt = $pdo->prepare('SELECT * FROM my_big_table LIMIT 100000');
$stmt->execute();
while ($rawCampaign = $stmt->fetch()) {
// echo $rawCampaign['id'] . "\n";
}
echo 'Ending with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";
Output:
Starting with memory usage: 6 MB
Ending with memory usage: 109.46875 MB
Here, the disappointing getIterator() method:
namespace Doctrine\DBAL\Driver\Mysqli\MysqliStatement
/**
* {#inheritdoc}
*/
public function getIterator()
{
$data = $this->fetchAll();
return new \ArrayIterator($data);
}
You can use my little library to actually stream heavy tables using PHP Doctrine or DQL or just pure SQL. However you find appropriate: https://github.com/EnchanterIO/remote-collection-stream

Using PHP to place database rows into an array?

I was just wondering how i would be able to code perform an SQL query and then place each row into a new array, for example, lets say a table looked like the following:
$people= mysql_query("SELECT * FROM friends")
Output:
| ID | Name | Age |
--1----tom----32
--2----dan----22
--3----pat----52
--4----nik----32
--5----dre----65
How could i create a multidimensional array that works in the following way, the first rows second column data could be accessed using $people[0][1] and fifth rows third column could be accessed using $people[4][2].
How would i go about constructing this type of array?
Sorry if this is a strange question, its just that i am new to PHP+SQL and would like to know how to directly access data. Performance and speed is not a issue as i am just writing small test scripts to get to grips with the language.
$rows = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$rows[] = $row;
}
Are you open to using a DB module, like the PEAR::DB module? If so, check out this article by Paul Dubois on Writing Scripts with PHP's Pear DB Module. The Module has been superseded, but it will show you the basics of some more advanced (and more commonplace) DB practices.
As for your actual question, you could iterate over all the rows and populate an array...
$dsn = "mysqli://testuser:testpass#localhost/test";
$conn =& DB::connect ($dsn);
if (DB::isError ($conn)) { /* ... */ }
$result =& $conn->query ("SELECT * FROM friends");
if (DB::isError ($result)){ /* ... */ }
while ($row =& $result->fetchRow()) {
$people[] = $row;
}
$result->free ();
Or you could write an object which implements the ArrayAccess interface, requesting a particular row when you refer to that index. (This code could be completely wrong but here's my try)
class FriendsTable implements ArrayAccess {
function offsetGet($key) {
$result =& $conn->query ("SELECT * FROM friends LIMIT $key, 1",); // careful; this is vulnerable to injection...
if (DB::isError ($result)){ die ("SELECT failed: " . $result->getMessage () . "\n"); }
$people = null;
if ($row =& $result->fetchRow ()) {
$people = $row;
}
$result->free ();
return $people;
}
function offsetSet($key, $value) {
/*...*/
}
function offsetUnset($key) {
/*...*/
}
function offsetExists($offset) {
/*...*/
}
}
$people = new FriendsTable();
$person = $people[2]; // will theoretically return row #2, as an array
... or something.
$array = array();
$sql = "SELECT * FROM friends";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
while($row = mysql_fetch_assoc($res)) $array[]=$row;

Categories