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;
Related
hye, i'm having trouble in calling all the rows in one table. hope anyone could assist me solve the error:
<?php
require_once('database.php');
$result = mysql_query("SELECT * FROM events ");
while($row = mysql_fetch_array($result))
?>
I am not an expert on mysqli stuff (I use a Connection class I found somewhere which provides functions like selectMultipleRows($query) and so on) but I will try to give a good answer here.
assuming you already have created a connection $this->connID
$mysqli = $this->connID;
$result = $mysqli->query($query);
$data = $result->fetch_all(MYSQLI_ASSOC);
//stuff I do to make my life easier:
$return = array(); //for scoping reasons
if (isset($data[0]['id'])) {
foreach ($data as $value) {
$return[$value['id']] = $value;
}
} else {
$return = $data;
}
as far as I am concerned this should work.
edit
my class Connection basically works like this:
$this->connID = new mysqli($this->server, $this->user, $this->pass, $this->database);
if ($this->connID→connect_errno) { //debug stuff
var_dump($this->connID->connect_error);
}
$this->connID->set_charset("utf8");
I guess this is all you will need.
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;
}
I'm fairly new to PHP and I've been looking around and can't seem to find the specific answer I'm looking for.
I want to make a SQL query, such as this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
// Create my array here ... I'm thinking of maybe having to
// make a class that can hold everything I need, but I dunno
while($row = mysqli_fetch_array($result))
{
// Put the row into an array or class here...
}
mysqli_close($connection);
// return my array or class
Basically I want to take the entire contents of the result and create an array that I can access in a similar fashion as the row. For example, if I have a field called 'uid' I want to be able to get that via myData['uid']. I guess since there could be several rows, maybe something more like myData[0]['uid'], myData[1]['uid'], etc.
Any help would be appreciated.
You can do:
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
You might try to use mysqli_result::fetch_all() for arrays:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
$array = $result->fetch_all();
$result->free();
mysqli_close($connection);
NOTE: This works with MySQLND only.
For class, you might try to use something like this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
while($model = $result->fetch_assoc()){
// Assuming ModelClass is declared
// And have method push() to append rows.
ModelClass::push($model);
}
$result->free();
mysqli_close($connection);
OR this:
// Base Model - abstract model class.
class ModelClass extends BaseModel {
// constructor
public function __construct(mysqli &$dbms){
// $this->dbms is MySQLi connection instance.
$this->dbms = &$dbms;
// $this->models is buffer for resultset.
$this->models = array();
}
// destructor
public function __destruct(){
unset($this->dbms, $this->models);
}
public function read(){
$result = $this->dbms->query($command);
if($this->dbms->errno){
throw new Exception($this->dbms->error, $this->dbms->errno);
}
$this->models = $result->fetch_all();
$result->free();
}
}
//object oriented style mysqli
//connect to your db
$mysqli = new mysqli("host", "user", "password", "dbname");
$result = $mysqli->query("SELECT * FROM `table`");
//use mysqli->affected_rows
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result->fetch_assoc();
}
//this will return a nested array
echo "<pre>";
print_r($rows);
echo "</pre>";
edit this and put it on a class and just call it anytime you're going to make a query with your database.
fetch_array: https://www.php.net/manual/en/mysqli-result.fetch-array.php
$result = $mysqli_connection->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
print_r($row);
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.
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) {
/* ... */
}