call data from database without mentioning specific rows - php

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.

Related

PHP and PDO - Migrated from MySQL - Not Showing Results or Errors

I'm migrating parts of my code from mySQL over to PDO and I can't seem to see what is wrong with my code.
I've got a try/catch statement and error reporting on, but i'm getting nothing at all.
Can anyone here see what is wrong?
The files that are relevant to this question are:
db_pdo.php
<?php
// Define connection
$db_host = "localhost";
$db_name = "winestore";
$db_user = "user";
$db_pass = "pass";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
search.php
<?php
require_once ("MiniTemplator.class.php");
function getSearch($tableName, $attributeName) {
try {
require ("db_pdo.php");
$query = "SELECT DISTINCT {$attributeName} FROM {$tableName} ORDER BY {$attributeName}";
return $db->query($query);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
}
function generatePage(){
$t = new MiniTemplator;
$t->readTemplateFromFile ("search_template.htm");
$rows = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('regionName', $row['region_name']);
$t->addBlock("regionName");
}
$rows = getSearch("grape_variety", "variety");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('variety', $row['variety']);
$t->addBlock("variety");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('minYear', $row['year']);
$t->addBlock("minYear");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('maxYear', $row['year']);
$t->addBlock("maxYear");
}
$t->generateOutput();
}
generatePage();
?>
You are storing in $rows, but you are using $result afterwards, which will be empty.
// $rows = getSearch("region", "region_name");
// should be this:
$result = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
Side note: You are creating a new database connection with every search. You should store your $db object and reuse it, instead of creating new instances of it. I'd recommend to wrap all these functions in a class where you store it, but since you stated that you are migrating existing code you could use global $db to pull the existing object into the variable scope of your function:
// include this file once at the beginning of your script
require_once("db_pdo.php");
function getSearch($tableName, $attributeName) {
global $db; // pull $db inside the variable scope
try {
// ...
Try it?
$rows = getSearch("region", "region_name");
but
$result->fetch(PDO::FETCH_$rows->fetch(PDO::FETCH_ASSOC)){ )){
to
$rows->fetch(PDO::FETCH_ASSOC)){

display all the rows retrieved by php from mysql db using function?

Class function that is retrieving values from db
public function retrieveFun()
{
include 'inc/main.php';//connecting to db.
$result = mysqli_query($con,"SELECT * FROM db order by name DESC");
while($row = mysqli_fetch_array($result))
{
$var = array('name' =>$row['name'] ,
'owner'=>$row['owner'],
'date'=>$row['date'] );
// echo $var["name"]."<br/>";
// echo $var["owner"]."<br/>";
// echo $var["date"]."<br/><br/>";
return array($var["name"],$var["owner"],$var["date"]);
}
}
and code where I want to display all the rows retrieved in desired format
$obj = new classname();
$id= $obj->retrieveFun();
echo //here i want to display all the rows retrieved in table format.
Please help me out as soon as possible
You've got return statement inside while loop, it has no sense. Try to put return statemanet outside the loop. To retrive result in table format i would do :
public function retrieveFun()
{
include 'inc/main.php';//connecting to db.
$result = mysqli_query($con,"SELECT * FROM db order by name DESC");
$resutlArray = array();
while($row = mysqli_fetch_array($result))
{
array_push($resultArray, $row);
}
return $resultArray;
}
Then to display your result in table format use :
$rows = $obj->retrieveFun();
echo '<table>';
foreach( $rows as $row )
{
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['owner'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '</tr>';
}
echo '</table>';
Put the return call outside your while loop. At the moment, only the first result would be stored before being returned. What you want to do is populate $var first before returning the variable.
When displaying the rows:
$rows = $obj->retrieveFun();
foreach( $rows as $key => $row ) {
echo $row[$key]['name'];
echo $row[$key]['owner'];
echo $row[$key]['date'];
}
See modification for $key support.
EDIT:
Also, when fetching the results, store them in an array.
$var = array();
while ( $row = mysqli_fetch_array( $result ) ) {
$var[] = array( ... );
}
http://www.w3schools.com/Php/php_mysql_select.asp
W3C is an amazing site for beginners. That page I linked has exactly what you need. It has examples and the source code all there to see, plus explanations. Read the examples and it'll explain it and you should be able to understand it.
If not, feel free to message me and I'll do what I can.
W3C has many tutorials that can cover just about all aspects of web, browse and be amazed!
It's good to check around the web before posting questions. We're here to help, but only if you try to help yourself first.
Hope it helps.
If you got your answer from this, please vote it up and mark it as the answer so others can find it easier.
Note: It's in the second section under 'Display the Result in an HTML Table'.
I really like the PDO approach over MySQLi it's much cleaner. Here's what I would do. A class with the DB connection and a public function inside the class.
Class + Function
class Database
{
private $db = null;
public function __construct()
{
$this->db = new PDO('mysql:host=localhost;dbname=pdo', 'root', 'password');
}
public function retrieveFun()
{
$query = $this->db->prepare("SELECT * FROM db ORDER BY name DESC");
$query->execute();
return $query->fetchAll();
}
}
Then to retrieve data I use foreach
if (retrieveFun()) { //Verify if the DB returned any row
foreach (retrieveFun() as $key => $value) {
echo $value->name . "<br />";
echo $value->owner . "<br />";
echo $value->date . "<br /><br />";
}
} else {
echo 'No data found.';
}
If you want to set up the connection in your main.php you can do the following:
//This section goes in the main.php file
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'db_name');
define('DB_USER', 'root');
define('DB_PASS', 'password');
//You can then call the defined constants like this
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);

Convert SQL results into PHP array

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

For and While loop in php mysql

I have the following code. Is there any way to combine and simplify it?
The output in the json.html file should be like this: ["abc","def","ghi"].
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "admin") or die(mysql_error());
mysql_select_db("test1") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM test_auto_complete") or die(mysql_error());
$menu = array();
while($row = mysql_fetch_assoc($result))
{
$menu[] = array("id" => $row['username'],);
}
foreach($menu as $key=>$value)
{
$menu[$key] = $value['id'];
}
$my_json_content = json_encode($menu);
$file = 'json.html';
$current = file_get_contents($file);
file_put_contents($file, $my_json_content);
?>
I know the code looks bad, but even so, can someone help me?
Thanks
Haan
If you want to put content in file than just use file_put_contents
$my_json_content = json_encode($menu);
$file = 'json.html';
file_put_contents($file, $my_json_content);
And use this while loop without foreach
while($row = mysql_fetch_assoc($result))
{
$menu[] = $row['username'];
}
I won't even give you solution with mysql_* because they are depracated look at the solution in PDO
<?php
$dsn = 'mysql:dbname=test1;host=127.0.0.1';
$user = 'root';
$password = 'admin';
try{
$dbh = new PDO($dsn, $user, $password);
$menu = array();
foreach ($conn->query("SELECT * FROM test_auto_complete") as $row)
$menu[] = $row['username'];
file_put_contents('json.html', json_encode($menu));
}catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Tips:
Mysql_* functions are depracated and they don't support a lot of features of MySQL
Foreach in your case was senseless.
File_get_contents() in your code does not have any sense for me, what do you need the content of file for?
Variables are used for data which is going to be changed. For example in your case you use variable for json.html which seems to be constant, if so, then use constant string.

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