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);
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.
I'm a newbie in oop style. I start practicing it since last week and I make simple CRUD website. but i got a problem when i tried fetching rows from mysql db its always display 1 row.
my created a class named class.user.php
and it shows here:
include "db_config.php";
class User{
private $db;
public function __construct(){
$this->connect();
}
private function connect($db_connect=true){
if ($db_connect){
$this->db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit;
}
}
}
public function get_tutoriallist(){
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
try {
$stmt = $this->db->prepare('SELECT * FROM `topic`');
$stmt->execute();
$result = $stmt->get_result();
$dataArray = array();
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
}
return ($dataArray);
mysqli_close($db);
$this->db = null;
} catch (Exception $e) {
echo $e->errorMessage();
}
}
}
and i call it using this:
$data = $user->get_tutoriallist();
if (!empty($data)) {
foreach ($data as $row){
echo "<tr>";
echo"<td>".$row['category']."</td>";
echo"<td>".$row['title']."</td>";
echo"<td>".$row['detail']."</td>";
echo"<td>".$row['photo']."</td>";
echo"<td>".$row['video_link']."</td>";
echo"<td>".$row['date_post']."</td>";
echo"<td class='option'><center><a href ='#' class='edit'>Edit</a>
<a href='#'>Delete</a></center></td>";
echo "</tr>";
}
}else{
echo '<tr><td colspan="6"><center><h2>No entries</h2></center></td></tr>';
}
I'm not quite sure what is going on here:
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
But normally, you just iterate through the results and append them to an array:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Then your $datArray has all the rows in it.
This is because you are appending to the result array only when $current_row == 1.
Try changing your while loop like this:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Also, you are not closing the db connection correctly, you are mixing OOP style with procedural mysqli functions. This is how it should be:
$this->db->close();
$this->db = null;
Finally, you should return the data array after you closed the connection. If you returned the data array first and closed the connection after, that code wont get executed.
So your last three lines should look like this:
$this->db->close();
$this->db = null;
return $dataArray;
I am new to writing web services and I cannot seem to figure this out! I have a simple php restful service that returns a json response, but I don't have any keys in the response (I don't know if that's the right term) What I get is something like this.
(
(
"name",
qty,
"image",
"price",
"date"
)
I am positive I am doing something wrong here.
Here is my service:
<?php
header('Content-type: application/json');
class InventoryAPI {
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'user', 'pass', 'dbname');
$this->db->autocommit(FALSE);
}
function __destruct() {
$this->db->close();
}
function checkInv() {
$query = "SELECT model, sku, quantity, stock_status_id, image, price, date_available FROM table_name";
$result = $this->db->query($query);
$rows = array();
$i = 0;
while($row = $result->fetch_row())
{
$rows[] = $row;
$i++;
}
$result->close();
$this->db->close();
echo json_encode($rows);
}
}
$api = new InventoryAPI;
$api->checkInv();
?>
I'm assuming you will want to use fetch_assoc() instead of fetch_row(). fetch_assoc() will return an array with keys the same name as the columns. fetch_row() will return an enumerated array based on the column position. For example: model is 0, sku is 1.
You can always test this out by printing out the array.
while($row = $result->fetch_row())
{
print_r($row);
}
I'm a beginner in OOP PHP.
I'm trying to make a class that will connect,query and fetch data
I done the below coding
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con= mysql_connect($this->host, $this->username, $this->password);
if(!$con){ die("Couldn't connect"); }
}
public function Database($set_database)
{
$this->database=$set_database;
mysql_select_db($this->database)or die("cannot select Dataabase");
}
public function Fetch($set_table_name){
$this->table_name=$set_table_name;
$query=mysql_query("SELECT * FROM ".$this->table_name);
$result= mysql_fetch_array($query);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
what I'm trying to achieve is this
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
and I want to fetch the data using a format like this
echo $result[0];
but I'm not getting that logic to make this happen
please help
Thanks!
Your Fetch function is only pulling one row from the database, and you aren't returning the results...
The method isn't the best, but in order to achieve what you're trying to do:
public function Fetch($set_table_name){
$query=mysql_query("SELECT * FROM ".$set_table_name);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
This will make each row a part of $result, but you'll have to access it like this:
You would call the fetch function like this:
$result = $connect->Fetch('posts');
echo $result[0]['columnName']; // for row 0;
Or in a loop:
for ($x = 0; $x < count($result); $x++) {
echo $result[$x][0] . "<BR>"; // outputs the first column from every row
}
That said, fetching the entire result set into memory is not a great idea (some would say it's a very bad idea.)
Edit: It also looks like you have other issues with your class... I have to run but will check back tomorrow and if others haven't set you straight I will expand.
Edit2: Ok, going to do a once-over on your class and try to explain a few things:
class MySQL {
//declaring the private variables that you will access through $this->variable;
private $host;
private $username;
private $password;
private $database;
private $conn; // Adding the connection, more on this later.
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// Combining the connection & connection check using 'or'
// Notice that I removed the semi-colon after the mysql_connect function
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function Database($set_database)
{
$this->database=$set_database;
// Adding the connection to the function allows you to have multiple
// different connections at the same time. Without it, it would use
// the most recent connection.
mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase");
}
public function Fetch($table_name){
// Adding the connection to the function and return the result object instead
return mysql_query("SELECT * FROM ".$table_name, $this->conn);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$posts = $connect->Fetch('posts');
if ($posts && mysql_num_rows($posts) > 0) {
echo "Here is some post data:<BR>";
while ($record = mysql_fetch_array($posts)) {
echo $record[0]; // or a quoted string column name instead of numerical index.
}
} else {
echo "No posts!";
}
I hope this helps... It should get you started at least. If you have more questions you should ask them separately.
That's because $result is set inside the Fetch function. It won't be available outside the Fetch function.
Instead of this line $result= mysql_fetch_array($query);, you'll want something like return mysql_fetch_array($query);.
And then in your code
$row = $connect->Fetch('posts');
// do something with $row
On another note, your Fetch function only applies to database queries that return one row. You'll have to separate the mysql_query & mysql_fetch_array calls into another function if you want to loop through rows in a query result.
And on another note, you shouldn't need to encapsulate this code into a class. PHP already provides OOP-based database classes called PDO, or PHP Data Objects. There's a learning curve to it, but it's best practice, and will help secure your code against things like SQL injection.
This is a pretty good tutorial: http://www.giantflyingsaucer.com/blog/?p=2478
I would make a function that returns the value of the object.
public function returnData($data){
return $this->$data;
}
Then within the page you wish to get the data on just initiate the class and call the function within that class.
$post->returnDate("row name here");
<?php
//database.php
class Databases{
public $con;
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "giit");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insert($table_name, $data)
{
$string = "INSERT INTO ".$table_name." (";
$string .= implode(",", array_keys($data)) . ') VALUES (';
$string .= "'" . implode("','", array_values($data)) . "')";
if(mysqli_query($this->con, $string))
{
return true;
}
else
{
echo mysqli_error($this->con);
}
}
public function selectmulti($selecttype,$table_name)
{
$array = array();
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
public function selectsingle($selecttype,$table_name)
{
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
$row = mysqli_fetch_assoc($result);
return $row;
}
}
?>
<?php
$data = new Databases;
$post_data = $data->selectmulti('*','centerdetail');
$n = 1;
foreach($post_data as $post)
{
echo $n.'.'.$post['CenterCode'].'___';
$n += 1;
}
echo '<br>';
$post_data = $data->selectsingle('*','centerdetail');
echo $post_data['CenterCode'];
?>
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;