PHP - How to 'parse data' from database using one method - php

I have tried a few different ways to make this work to no avail.
Basically, I have these 4 lines that are in many functions:
function getID($URL){
//These 3 plus this comment line
$parentQ = "select * from cdi_content where URL=\"$URL\"";
$parentResult = mysql_query($parentQ); // Run the Query
$link = mysql_fetch_assoc($parentResult); // Query Result
...continues...
That basically tells the database to check $URL and if it matches the URL string in the database, it grabs all of the data associated with that URL, and I grab what I need with
$link['ID'];
Which would give me the ID associated with the $URL URL.
The function checks a list of conditionals that either print the 'override' variable ($ID), the default variable ($defaultID) or pulls from the server ($link['ID']), like below. The 'override' is a variable outside of the function that is currently called in by global $ID.
$ID = ''; //Overrides if set
function parseData($URL){
//Initialize Query for Table Data
$parentQ = "select * from cdi_content where URL=\"$URL\"";
$parentResult = mysql_query($parentQ); // Run the Query
return mysql_fetch_assoc($parentResult); // Query Result
};
function getID($URL){
global $ID;
$serverID = parseData($URL);
if(empty($ID)){
if(empty($serverID)){
echo $defaultID;
} else { echo $serverID['ID']; }
}//end of ifs
else
{ echo $ID; }
};

So you you want to parse the data row you would need search criteria $criterion and a field you you want it to return:
function getField($criterion, $returnField){
$parentQ = "select * from cdi_content where URL='".$criterion."' LIMIT 1"; // also make sure you that $criterion is safe to use in a query
$parentResult = mysql_query($parentQ); // Run the Query
if ($parentResult)
{
$row = mysql_fetch_assoc($parentResult);
return $row[$returnField];
}
else
{
return FALSE;
}
}
Now you can call it:
$linkId = getField($url, 'ID');

If I'm understanding you correctly, you're just trying to refactor that function so you don't have to keep on re-writing it. Is that correct?
If so, you can extract a new function like this:
function getLink($URL){
$parentQ = "select * from cdi_content where URL=\"$URL\"";
$parentResult = mysql_query($parentQ); // Run the Query
return mysql_fetch_assoc($parentResult);
}
And then call it like this:
function getID($URL){
$link = getLink($URL);
}

Related

the data do not display in my view

Undefined variable: data in my view
This is a simple display data in the input.
So, why this input isn't display my query result at it?
my view
<input type="text" name="sitename" value="<?php echo $data['sitename']; ?>"><br>
model
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
$num = mysqli_num_rows($sqli);
while ($num > 0)
{
$data = mysqli_fetch_array($sqli);
$num--;
}
return $data;
}
}
Simply because a variable is declared somewhere, doesn't mean it is available everywhere. All variables have scope in which they are accessible. See this: http://php.net/manual/en/language.variables.scope.php for more information on scope.
You need to pass the $data variable into your view. I image you're using some sort of MVC framework since you have a model and a view. If this is the case you can lookup how to pass variables into views in that specific framework. The basic structure of your controller method might look something like this:
//sudo code - not specific to an actual framework
public function controller_method()
{
$data = $model->getData();
$this->template->set('data',$data);
$this->template->load('view');
}
Just search how to do that in your specific framework. Hope that helps!
EDIT
Base on your comment it looks like you're setting data after you load the view. You need to swap the order and call $display = new Display("main"); $data = $display->getData(); before you include'../model/display.php';
If the query returns 0 rows, your while() loop will never execute, so it won't set $data.
Since you're only returning 1 row from the query, you don't need a loop, you can just use an if. Then you can return $data only when it succeeds.
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
if ($data = mysqli_fetch_array($sqli))
{
return $data;
}
else
{
return null;
}
}
}

Cannot get data from mysql query to controller

Hello I am using codeigniter framework for a project, I have a controller which is calling the data from a model function. Here is the controller.
public function getThirdPartyRR($token){
if ($this->input->is_ajax_request()){
// $data = json_decode(file_get_contents('php://input'), true);
// Following is loaded automatically in the constructor.
//$this->load->model('user_profile');
$userid = $this->myajax->getUserByAuth($token);
if ($userid){
$this->load->model("riskrating_page");
/* If we have an impersonated user in the session, let's use him/her. */
if (isset($_SESSION['userImpersonated'])) {
if ($_SESSION['userImpersonated'] > 0) {
$userid = $_SESSION['userImpersonated'];
}
}
// $resultList value could be null also.
$result = $this->riskrating_page->getThirdPartydata($userid);
/* Little bit of magic :). */
$thirdpartylist = json_decode(json_encode($result), true);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($thirdpartylist));
} else {
return $this->output->set_status_header('401', 'Could not identify the user!');
}
} else {
return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
}
}
And here is the query function in the model where I get the data from.
function getThirdPartydata($id){
$query = 'SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = \'user_thirdparty_rr\'
WHERE a.Owner = '.$id. ' and
a.UPDATE_DT is null;';
}
But when I debug it using netbeans, its shows that in my controller in the $result function I get null meaning I couldnt grab any data from mysql.
Here is the search result from mysql.
You only write your query not fetch any data from your query result
function getThirdPartydata($id){
$query = "SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = 'user_thirdparty_rr'
WHERE a.Owner = '$id' and
a.UPDATE_DT is null";
$this->db->query($query);// execute your query
return $query->result_array();// fetch data
}

Efficient way to reuse the same call to the same sql table

So I search for this title hoping someone would have already answered it however, I came across similar topics on other languages but not PHP so maybe this will help others.
I am constantly using this following script to call on the database but how can I create it so that I can make it just once at the top of the class for example and use it in every method on the class page that needs it. Example: An single page may not have all of the data it needs from the same table but if the table contains 50% of the data or more for that page, how can I modify this so that I can just say it once and let the rest of the following scripts display the data it extracted in the first place by calling it all just once?
Here's what I have now.
<?php
if($res = $dbConn->query("SELECT Column FROM Table")){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
?>
I want to call on this without the printf(" "); collect and store the data so that I can then call the results while printing or echoing the results with the HTML in other methods. What os the most efficient way? I don't want to make the same call over and over and over... well, you get the point.
Should I use fetch_array or can I still do it with fetch_assoc?
not very sure if it's the answer you want.
you can use include/include_once/require/require_once at the top of the page you want to use the function
for example:
general_function.php:
-----
function generate_form( $dbConn, $sql ) {
if($res = $dbConn->query("SELECT Column FROM Table")) {
while($d = $res->fetch_assoc()) {
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
and for those pages you want to use the function, just put
include "$PATH/general_function.php";
and call generate_form
Try this:
class QueryStorage {
public static $dbConn = null;
public static $results = [];
public static function setConnection($dbConn) {
self::$dbConn = $dbConn;
}
public static function query($query, $cache = true) {
$result = (array_key_exists($query, self::$results))?
self::$results[$query] : self::$dbConn->query($query);
if($cache) {
self::$results[$query] = $result;
}
return $result;
}
public static function delete($query) {
unset(self::$results[$query]);
}
public function clean() {
self::$results = [];
}
}
usage:
at top somewhere pass connection to class:
QueryStorage::setConnection($dbConn);
query and store it:
$result = QueryStorage::query("SELECT Column FROM Table", true);
if($result){
while($d = $result->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
reuse it everywhere:
$result = QueryStorage::query("SELECT Column FROM Table", true); // it will return same result without querying db second time
Remember: it's runtime cache and will not store result for second script run. for this purposes You can modify current class to make it
work with memcache, redis, apc and etc.
If I understood you correctly, then the trick is to make an associative array and access with its 'key' down the code.
$dataArray = array();
// Add extra column in select query for maintaining uniqness. 'id' or it can be any unique value like username.
if($res = $dbConn->query("SELECT Column,id FROM Table")){
while($d = $res->fetch_assoc()){
$dataArray[$d['id']] = $d['Column'];
}
}
//you have value in the array use like this:
echo $dataArray['requireValueId'];
//or , use 'for-loop' if you want to echo all the values
You need a function which takes in the query as a parameter and returns the result.
Like this:
public function generate_query($sql) {
if($res = $dbConn->query($sql)){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}

Getting table object(App_Model_TableName) as fetch result (Zend Framework)

Right now, I'd wrote a function in my model as:
public function getRowsByZipCode($zip)
{
// SQL to get all the rows with the given zip code
$stmt = $this -> getAdapter()
-> query( "SELECT *
FROM
table_name
WHERE
table_name.status = 1 AND
table_name.zip={$zip}");
$resultRows = $stmt->fetchAll();
// -------------------------------------------------------- //
// Convert result set to an array of objects
$resultObjects = array();
// If there is atleast one row found in DB
if(count($resultRows) > 0)
{
// Loop throguh all the rows in the resultset
foreach($resultRows as $resultRow) {
// Create table row and fill it with the details got from DB
$h = $this->createRow();
$h->setFromArray($resultRow);
// Add to the array
$resultObjects[] = $h;
}
}
return $resultObjects;
// -------------------------------------------------------- //
}
Which is working perfectly as I needed. And it is returning me an array that contains the tables row objects(App_Model_TableName Objects), which will be used later for further operations like save and delete etc.
What I really want is to remove the code that loop through the rows I got from the result set and converting each row to an object of App_Model_TableName that I'd wrote inside the comments // --- //.
Thanks in advance.
Firstly, I am assuming you are using PDO.
Try the following
class App_Model_TableName
{
public $status;
public $zip;
// public $other_column;
}
class YourClass
{
protected function getAdapter()
{
// Do adapter stuffs
}
public function query($query, array $param)
{
// When Using PDO always use prepare and execute when you pass in a variable
// This will help prevent SQL injection
$stmt = $this->getAdapter()->prepare($query);
return $query->execute($param);
}
/**
* #return App_Model_TableName[]
*/
public function getRowsByZipCode($zip)
{
// SQL to get all the rows with the given zip code
// This way will help prevent SQL injection
$query = "SELECT * FROM table_name WHERE table_name.status = 1 AND table_name.zip = :zip";
$qData = array(':zip' => $zip);
$results = $this->query($query, $qData);
return $results->fetchAll(PDO::FETCH_CLASS, 'App_Model_TableName');
}
}
Calling YourClass::getRowsByZipCode() will then return you an array of App_Model_TableName objects. You can then access them like:
$data = $instance_of_yourclass->getRowsByZipCode(12345);
foreach ($data as $row)
{
echo $row->zip;
echo $row->do_stuff();
}
All these awesome functions I found on:
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/pdostatement.execute.php
Disclaimer: this code was not tested :(
Be cool but stay warm
Finally, I had found the solution:
public function getRowsByZipCode($zip)
{
// SQL to get all the rows with the given zip code
$stmt = $this -> getAdapter()
-> query( "SELECT *
FROM
table_name
WHERE
table_name.status = 1 AND
table_name.zip={$zip}");
$resultObjects= array();
while($data = $stmt->fetch())
{
$h = $this->createRow();
$h->setFromArray($data);
// Add to array
$resultObjects[] = $h;;
}
return $resultObjects;
}
I had removed the code that do the fetchAll() and loop through each row in the resultset. Now, I am taking each row from the resultset and creating an row of App_Model_TableName object using the data we got from the resultset.
Working perfectly for me.

How to make PDO query work inside a function

I am try to make an PDO sql inside function but it doesn't work. got no response from it. it works when not using function. my purpose is to make my code small. anyone can shed a light. thanks.
function Test() {
$get_name = $smt->prepare("SELECT * FROM customer WHERE id = '1'");
$get_name->execute();
foreach ($get_name as $temp) {
$name = $temp['name'];
$address = $temp['address'];
$phone = $temp['phone'];
$page = $temp['page'];
}
eval("\$page = \"$page\";");
echo $page;
eval("\$page = \"$page\";");
echo $page;
}
Test();
I'd probably refactor your code to something like:
function getCustomerInfo(PDO $pdo, $customerId)
{
// use a prepared statement that can get you info on any customer
$statement = $pdo->prepare(
"SELECT * FROM customer WHERE id = :customerId LIMIT 1");
// get the result resource from the database
$result = $statement->execute(array(
':customerId' => $customerId
));
// fetch the first row in the result as an associative array
// and return it to the caller.
return $result->fetchFirst(PDO::FETCH_ASSOC);
}
// use your connection in place of $pdo
$customerData = getCustomerInfo($pdo, 1);
// now you can do stuff with your data
var_dump($customerData);
This is better because it does not rely on global state, functions should never-ever-ever do that. and it uses prepared, parameterized sql that makes it faster and the function more useful for customers other that the one where id=1.
You need to make the pdo instance global within the function
function Test() {
global $smt;

Categories