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);
Related
I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -
try{
///try to connect with database
$conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo "error";
}
$mysqlcode="SELECT * FROM users";
$ret=$conn->query($mysqlcode);
foreach($ret as $ret1)
print $ret1->id;
in the browser,
showing this error:
Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44
In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.
I have checked your code. Everything is fine. Just do this.
foreach($ret as $ret1)
print $ret1['id'];
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code
$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);
if ($ret->num_rows > 0) {
// output data of each row
while($row = $ret->fetch_assoc()) {
echo "id: " . $ret["id"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
that'll work fine.
Before trying to use Object Oriented PHP, is much easier to understand Procedural. Take a look at the code below.
First, connect to database:
<?php
//Store log in info into variables
$servername = 'localhost';
$serveruser = 'youruser';
$serverpassword = 'yourpassword';
$serverdatabase = 'yourdatabase';
// Create connection
$conn = mysqli_connect( $servername, $serveruser, $serverpassword, $serverdatabase );
if ( !$conn ) {echo "Connection Fail" . mysqli_connect_error();}
//else {echo "Connected to database $serverdatabase";}
?>
Then, call the information from your database and your table and store it into an associative array $data
$sql = "SELECT * FROM `table`";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASOCC);
mysqli_free_result($result);
Now you can use the array to print the results with print_r
echo '<pre>'; print_r($data); echo '</pre>';}
Now you are ready to use foreach depending on your table columns,for example if you have ID column then
<?php foreach ($data as $value){
echo $value['id]."<br>";
} ?>
It will print out all the IDs. Hope this helps.
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 made a function to fetch a column and them render each row as a li.
But I am getting "Errormessage:" as result. I tried it without functon and that works fine.
Please help.
$nkFetch = function($link){
$table1Query = "SELECT * FROM table1";
$res = mysqli_query($link, $table1Query);
if (!mysqli_query($link, $table1Query)) {
printf("Errormessage: %s\n", mysqli_error($link));
}
$table1 = array();
while ($row = mysqli_fetch_array($res)){
$table1[] = $row;
}
shuffle($table1);
foreach( $table1 as $row ){
echo "<li>" . $row['WORD'] . "</li>";
}
}
Update
Given that you're using a lambda-style function (instance of Closure), and wish to use a globally available variable $link, you should write:
$nkFetch = function () use ($link)
{
//code here. $link is available
};
$nkFetch();
//or
$nkFetch = function ($link)
{
//code here
};
$nkFetch($link);//<-- pass mysqli here
Read the manual on anonymous functions
Very well, I'll bite.
You say this is a function. If so: are you passing the $con connection variable as an argument
Have you made sure the connection (mysql_connect call) was successful
As an asside: mysql_free_result really is a tad pointless if that's the last statement in your function. The resultset should be freed once all function variables go out of scope
Now, here's what your code should look like if you want to use that deprecated extension (BTW: try updating your PHP version, and set your error level to E_STRICT | E_ALL, you should see deprecated notices).
Assuming this is indeed a bona-fide function:
function getList($con)
{
if (!is_resource($con))
{//check if $con is a resource, if not... quit
echo '$con is not a resource!', PHP_EOL;
return;
}
$res = mysql_query('SELECT * FROM table1', $con);
if (!$res)
{//query failed
echo 'Query failed: ', mysql_error($con);
return;
}
while($row = mysql_fetch_assoc($res))
{//echo here already
echo '<li>', $row['WORD'], '</li>';
}
}
//call like so:
$dbConnection = mysql_connect('127.0.0.1', 'user', 'pass');//pass your params here, of course
if (!$dbConnection) exit(mysql_error());
getList($dbConnection);
A more modern way of writing this would be:
$db = new PDO('127.0.0.1', 'user', 'pass');
$res = $db->query('SELECT * FROM table1');
while($row = $res->fetch(PDO::FETCH_ASSOC))
{
echo '<li>', $row['WORD'], '</li>';
}
Check the PDO documentation
I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];
I am selecting data from a database. The database field names are exactly the same as the class variable names. Is there a way to store this data into the class variables without specifying each one individually?
//gets info about a specified file.
//chosen based on a supplied $fileId
function getFileInfo($fileId)
{
//select info from database
$sql = "SELECT id, companyId, url, name, contentType, fileSize, saved, retrieved
FROM files
WHERE id = $fileId";
$results = $this->mysqli->query($sql);
$results = $results->fetch_object();
//store info into class variables
$this->id = $results->id;
$this->companyId = $results->companyId;
$this->url = $results->url;
$this->name = $results->name;
$this->contentType = $results->contentType;
$this->fileSize = $results->fileSize;
$this->saved = $results->saved;
$this->retrieved = $results->retrieved;
}
A quick and dirty way would ba a loop:
foreach($result as $var => $value) {
$this->$var = $value;
}
I'd propose this approach:
$nameMap = array(
'id',
'companyId',
'url',
'name',
'contentType',
'fileSize',
'saved',
'retrieved',
);
foreach( $nameMap as $attributeName ) {
$this->$attributeName = $results->$attributeName ;
}
While one could write
foreach($result as $var => $value) {
...
}
the outcome fully depends on backing table's structure. If you add further attributes to the table, your code might break.
Using $nameMap, the application still works.
Just use foreach structure:
foreach ($result as $column => $value) {
$this->$column = $value;
}
Not nice but will work.
Humm. Well, PDO has native functions for that, if you're not married to mysqli for some reason:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
The biggest disadvantage I've found is that PDO doesn't support SSL connections between the PHP machine and the MySQL machine.