PHP PDO for getting MySQL fileds name - php

I have a function from class that gets data from MySQL. All works OK but I also want to know how I can get the column names for MySQL data.
Here is my code :
public static function getTickets(){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "select tickets.*,customers.* from tickets,customers where
(tickets.ticket_customer_id = customers.customer_id) order by tickets.ticket_open_date desc ";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while($row=$st->fetch()) {
$tickets = New Tickets($row);
$list[] = $tickets;
}
//total rows of customer
$sql = "select FOUND_ROWS() as totalRows";
$totalRows = $conn->query($sql)->fetch();
$conn=null;
$columnCount = $st->columnCount();
//pass the values to page
return (array("results"=>$list ,"totalRows"=>$totalRows,"columnCount"=>$columnCount));
}

It's hard to tell what you need here, but looking at your code I would say that everything you need you can get from the very data you are fetching
public static function getTickets($conn){
$sql = "select tickets.*,customers.* from tickets,customers where
(tickets.ticket_customer_id = customers.customer_id) order by tickets.ticket_open_date desc ";
$st = $conn->query($sql);
$list = array();
while($row=$st->fetch(PDO::FETCH_ASSOC)) {
$list[] = New Tickets($row);
$columnNames = array_keys($row);
}
//total rows of customer
$totalRows = count($list);
$columnCount = count($columnNames);
//pass the values to page
return (array("results"=>$list ,"totalRows"=>$totalRows,"columnCount"=>$columnCount));
}

Related

Computing sum of 2 fields in a table using MySQL fetch function in PHP

I have a table having the following fields: id(Autoincrement/Primary Key)/Integer1/Integer2/Sum/Product). I have filled integer1 and integer2 with the following code:
for ($i=1;$i<=1000;$i++)
{
$x2=rand(0,100);
$x3=rand(0,100);
$sql="INSERT INTO data(integer1,integer2) VALUES ($x2,$x3)";
$conn->query($sql);
}
I need help to prepare a function which uses MySQLFetch and computes sum of integer1 and integer2 and assigns the value in sum and product. I know it can be done using a simple loop, but would really like to get an understanding of fetching data.
Assuming you are using mysqli which is how it appears with the use of $conn->query() then this might be of interest.
/* establish db connection */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* select records to to perform sum & product upon */
$sql='select * from `data`';
$res=$conn->query( $sql );
if( $res ){
/* prepare a new sql statement to update db records */
$sql='update `data` set `sum`=?, `product`=? where `id`=?;';
$stmt=$conn->prepare( $sql );
while( $rs=$res->fetch_object() ){
/* make some variables with records for each record */
$id=$rs->id;
$int_1=$rs->integer1;
$int_2=$rs->integer2;
/* basic maths operations */
$sum=$int_1+$int_2;
$product=$int_1 * $int_2;
/* bind the variables into declared statement & execute */
$stmt->bind_param( 'iii', $sum, $product, $id );
$stmt->execute();
}
/* tidy up */
$stmt->close();
$conn->close();
}
Kindly try the following example :
$db = new mysqli('localhost', 'root', 123456, 'data');
$query = 'SELCT * FROM tableName';
$objResult = $db->query($query);
while ($resultRow = $objResult->fetch_object()) {
$id = $resultRow->id;
$integer1 = $resultRow->integer1;
$integer2 = $resultRow->integer2;
$result = sumProduct($integer1, $integer2);
$sum = $result[0];
$product = $result[1];
$query = "UPDATE tableName SET
sum = '$sum',
product = '$product'
WHERE
id = $id";
$db->query($query);
$db->close();
}
function sumProduct($int1, $int2) {
$sum = $int1 + $int2;
$product = $int1 * $int2;
return array($sum, $product);
}
Is this way you expected?
$query = "SELECT * FROM data";
$row = mysql_query($query);
while($result = mysql_fetch_assoc($row))
{
$id = $result['id'];
$integer1 = $result['integer1'];
$integer2 = $result['integer2'];
$sum = $integer1 + $integer2;
$prod = $integer1 * $integer2;
mysql_query("UPDATE data SET sum=$sum,product=$prod WHERE id=$id");
}

Return associative array from function

This is how I would normally run a loop with database information
$query = "SELECT * from courses ORDER BY id DESC LIMIT 4";
$stmt = $db->prepare($query);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { }
Now $row[] can be used to represent database information within the loop.
My problem is that I'll be utilizing this query a lot for separate while loops. However, I don't wish to have to complete this statement every time I require it, so I want a function to be able to refer to with any variables required.
For instance, I tried.
function retrieve_assoc_array_limit4($table) {
$user = '***';
$pass = '***';
$db = new PDO('mysql:host=localhost;dbname=***', $user, $pass);
$query = ("SELECT * FROM ? ORDER BY id DESC LIMIT 4");
$stmt = $db->prepare($query);
$stmt->bindValue(?, $table);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row;
}
But when trying to while it I get an unlimited amount of returns of the same information whiled.
while($row = retrieve_assoc_array_limit4($table_name)) {
exho $data;
}
My question is how logically to use the first code in a function so that I can use it in the same with without writing out the full statement relentlessly.
many ways of doing this, to use your code with little changes:
calling fetchAll() instead of fetch():
function retrieve_assoc_array_limit4($table) {
$user = '***';
$pass = '***';
$db = new PDO('mysql:host=localhost;dbname=***', $user, $pass);
$query = ("SELECT * FROM ? ORDER BY id DESC LIMIT 4");
$stmt = $db->prepare($query);
$stmt->bindValue(?, $table);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
then call your function and do a while or foreach:
$rows = retrieve_assoc_array_limit4($table_name);
foreach($rows as $row){
//do your stuff
}

how to properly use while loop in PDO fetchAll

please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to PDO.
so i have a function to get the contents from my database
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($sql);
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
normally when i return $row in mysqli, i would define fetch_assoc() in my while loop.
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$content = $row['content'];
}
Now, since (PDO::FETCH_ASSOC) is already declared in my function.
how would i properly create my while loop to print the values in PDO?
[edit]
updated code
i will be declaring my while loop outside of the function. so i need something to return from my function but i dont know what that is..
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$row = $sql->execute();
return $row;
}
this is my while loop outside the function.
$sql = getContent();
while ($row = $sql->fetchAll(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$content = $row['content'];
}
With fetchAll() you don't have to use while at all. As this function returns an array, you have to use foreach() instead:
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent();
foreach($data as $row) {
$id = $row['id'];
$content = $row['content'];
}

How to Fetch Multiple rows from PHPMYADMIN using PHP Code

I have multiple record(s) in PHPMYADMIN and now i am trying to fetch those record(s) using PHP Code, but always i am getting Array ( ) 1 whenever i run my php script using Localhost, however i have 5 rows in table.
Please see below code:
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("mydatabase");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE
MemberID = '".mysql_real_escape_string($strMemberID)."' ORDER BY OrderID DESC ";
$objQuery = mysql_query($strSQL);
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr = array();
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo print_r($arr);
?>
change your code in while loop.
declare $arr outside the loop. declaring array inside loop will clear it before initializing. thats why you are getting a single row in each run.
$arr = array();
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
Also, to view array elements use echo json_encode($arr) or var_dump($arr) or print_r($arr);
it will definitely work for you
It's not directly an answer to your question but while you're at it try to use PDO and prepared statements
$strMemberID = $_POST["sMemberID"];
$strSQL = 'SELECT * FROM order_details WHERE MemberID = ? ORDER BY OrderID DESC';
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare($strSQL);
$query->execute(array($strMemberID));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo 'Exeption: ' .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
You may like it.

Returning Multiple Rows with MySqli and Arrays

For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.
$mysqli = new mysqli("localhost", "user", "password", "database");
function display_posts ($mysqli, $user_id) {
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
$user_id = (int)$user_id;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id
LIMIT 4";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row;
$result->free();
$stmt->close();
}}
Here I am trying to display the data.
$user_id = 1;
$posts = display_posts($mysqli, $user_id);
//Not sure what to do with $posts. A While loop perhaps to display each post?
You have to use a loop to get them all at once:
<?php
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
$result->free();
Why not use directly like this:
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
I'm late, but I believe this is what you wanted to achieve:
$mysqli = new mysqli("localhost", "user", "password", "database");
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
function display_posts () {
global $mysqli;
global $fields;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4";
$posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);
if ($posts -> num_rows > 0) {
while ($row = $posts -> fetch_assoc()) {
$value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];
echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';
}
}else {
echo 'No records found.';
}
}
//Call the function
display_posts ();

Categories