how to acess my database elements using the for loop? - php

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'];

Related

creating new db rows from data in array?

Hey guys im trying to pass some data from an (oracle) fetch_array to a variable array and then use that array data to check if the data exists on a mysql db and create any rows that dont currently exist.. this is what i have so far.
the problem is its only checks/creates 1 entry of the array and doesn't check/created the entire array data. i think i would need to use a for loop to process all the array data concurrently
<?php
$conn = oci_connect('asdsdfsf');
$req_number = array();
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, " SELECT WR.REQST_NO
FROM DEE_PRD.WORK_REQST WR
WHERE WR.WORK_REQST_STATUS_CD = 'PLAN' AND WR.DEPT_CD ='ISNG'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
// Use the uppercase column names for the associative array indices
$req_number[]= $row['REQST_NO'];
}
oci_free_statement($stid);
oci_close($conn);
//MYSQL
//Connection Variables
//connect to MYSQL
$con = mysqli_connect($servername,$username,$password,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// lets check if this site already exists in DB
$result = mysqli_query($con,"
SELECT EXISTS(SELECT 1 FROM wr_info WHERE REQST_NO = '$req_number') AS mycheck;
");
while($row = mysqli_fetch_array($result))
{
if ($row['mycheck'] == "0") // IF site doesnt exists lets add it to the MYSQL DB
{
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
if (mysqli_query($con, $sql)) {
$created = $req_number." Site Created Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}else{ // if site is there lets get some variables if they are present...
$result = mysqli_query($con,"
SELECT *
FROM wr_info
WHERE REQST_NO = '$req_number[0]'
");
while($row = mysqli_fetch_array($result))
{
$do some stuff
}
}
}
mysqli_close($con);
?>
You create an array:
$req_number = array();
And loop over records to assign values to the array:
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
$req_number[]= $row['REQST_NO'];
}
But then never loop over that array. Instead, you're only referencing the first record in the array:
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
// etc.
(Note: There are a couple of places where you directly reference the array itself ($req_number) instead of the element in the array ($req_number[0]), which is likely an error. You'll want to correct those. Also: You should be using query parameters and prepared statements. Getting used to building SQL code from concatenating values like that is a SQL injection vulnerability waiting to happen.)
Instead of just referencing the first value in the array, loop over the array. Something like this:
for($i = 0; $i < count($req_number); $i++) {
// The code which uses $req_number, but
// referencing each value: $req_number[$i]
}

PhP MySQL get ceratin items from database and echo them

I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}

Why do i get more results from my mysql query in php then what i ask for?

I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works

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

Getting errormessage only if using function in MYSQL

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

Categories