cannot insert query result into file - php

I try to insert result of query into some file.
The file is created but it contain nothing.
I check the query result and its working, i receive a result data.
here is my controller code :
$members_nik = array();
$members_nik = select_config_by('member', 'member_nik', 'WHERE 1=1');
file_put_contents("data.txt", implode(', ', $members_nik));
here is my function code :
function select_config_by($table, $obj, $where){
$query = mysql_query("SELECT $obj as result FROM $table $where");
$row = mysql_fetch_array($query);
$result = $row['result'];
return $result;}

You are returing a string from the select_config_by function but then trying to implode it as if it were an array.
Now assuming you want to return all the results and save them in your data.txt, change the function to this:
function select_config_by($table, $obj, $where)
{
$result = mysql_query("SELECT $obj as result FROM $table $where");
$temp = array();
while ($row = mysql_fetch_array($result))
{
$temp[] = $row['result'];
}
return $temp;
}

Related

problem in fetching data from tables of sql in PHP

hi i"ve created multiples tables in sql first time s i'm having difficulties in fetching data. so here is my code ,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
}
i'm only getting data from $result as i want to fetch data from $result 1-3.
i tried to run loop for all the result variables like this,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
// fetch product data one by one
while ($item1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
$resultArray[] = $item1;
}
return $resultArray;
// fetch product data one by one
while ($item2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
$resultArray[] = $item2;
}
return $resultArray;
// fetch product data one by one
while ($item3 = mysqli_fetch_array($result3, MYSQLI_ASSOC)){
$resultArray[] = $item3;
}
return $resultArray;
}
but i got the error which was ::undefined variable item1-3 in line no 74::
what should i do now.
You have some mistakes in your code, i somekind of "corrected" your code for you.
return statement exits your function means code below return is not executed
you can reuse variables
use multidimensional array to store multiple tables in one array
I know its not the best way to query the database - but i hope it helps you a little
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
$resultArray[$table] = array();
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
array_push($resultArray[$table], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$liner] = array();
while ($item = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
array_push($resultArray[$liner], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$eyeshadow] = array();
while ($item = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
array_push($resultArray[$eyeshadow], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$brush] = array();
while ($item = mysqli_fetch_array($result3, MYSQLI_ASSOC)){ //you can reuse $item
array_push($resultArray[$brush], $item);
}
return $resultArray;
}

How to fetch a table from MySQL in PHP

I'm a newbie to PHP and I'm just trying the very basics of MVC. Everything is going good but I have a problem while fetching data from MySQL and populating a HTML table with it.
The problem is that my code is just returning one row of the table (there are three rows in that table).
I have tried many things and right now I'm using arrays for storing the data and passing to controller and then to the view.
Query class file having a function for getting data and name queryDB:
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = "select * from tbl_cartypes";
$result = mysql_query($query) or die("Error: ".mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
return $data;
}
$connectObj->closeDB();
}
The controller class where the controller of this query is name carController.php:
public function getAllData(){
$runQuery = new queryDB();
$array = array();
$array = $runQuery->getTickets($userid);
return $array;
}
And the final view where I'm just echoing my data:
include "$path/controllers/carController.php";
$ticket = new carController();
$array = array();
$array = $ticket->getdata();
for($i=0;$i<count($array);$i++){
echo $array[$i]."<br />";
}
Output of this code is without error, but the problem is that it's just fetching one row of the table whereas there are three rows.
So any one can help me with this?
It's fetching all rows, but you're saving all the data to the same place ($data[0] through $data[5]), so all but the last row is getting overwritten.
This might work better:
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Using PDO and what other people have posted try using this
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = 'select * from tbl_cartypes';
$result = $connectObj->query($query);
$data = array()
foreach ($result as $row){
array_push($data, $row)
}
return $data;
}
$connectObj->closeDB();
}
Your problem is that you're overwriting the values of the previous table:
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
This will just re-write the last row of data over the key's in that table.
Try:
$data = array()
while($row = mysql_fetch_assoc($result)){
array_push($data, $row)
}
Your while loop is assigning just one row to array $data. in while loop instead try this
while($row = mysql_fetch_assoc($result)){
$data["car_id"][] = $row['car_id'];
$data["car_name"][] = $row['car_name'];
$data["car_model"][] = $row['car_model'];
$data["car_type"][] = $row['car_type'];
$data["car_price"][] = $row['car_price'];
}
return $data;
Now you can iterate through the array.

PHP mySQL query remove double array

In the example below I am taking an array of the ID's only to turn it into a while and then back into an array only to explode it on the comma on the page. Surely there must be an easier way of doing this.
I am after an array of the $row['ID']s
function get_other_elector_phone($telephone,$current,$criteria){
$the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
while($row = mysql_fetch_array($the_others)) {
$results .= $row['ID'].','; } return $results;
}
$others = get_other_elector_phone(g('electors',$elector,'telephone'),$elector,$criteria);
if($others){ $others = explode(',',$others);
just as #daverandom said, just rebuild an array, this is the syntax :
function get_other_elector_phone($telephone,$current,$criteria){
$the_others=mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria");
$results = array();
$i=0;
while($row = mysql_fetch_array($the_others)) {
$results [$i]= $row['ID'];
$i++;
}
//results returned outside loop
return $results;
}
$others = get_other_elector_phone(g('electors',$elector,'telephone'),$elector,$criteria);
The $others will return an array.
instead of
function get_other_elector_phone($telephone,$current,$criteria){
$the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
while($row = mysql_fetch_array($the_others)) {
$results .= $row['ID'].','; } return $results;
}
}
just return the result of mysql_fetch_array()
function get_other_elector_phone($telephone,$current,$criteria){
$the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
return mysql_fetch_array($the_others);
}
then there is no need to explode the output of the function.

PHP - how to use array in function?

I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function

PHP: letting your own function work with a while loop

$qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
$aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");
function vraagOp($table,$where)
{
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
$aVraagOp = mysql_fetch_assoc( $rVraagOp );
return $aVraagOp;
}
only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
echo "testing <br>";
}
It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
Is this possible?
This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
static $rVraagOp;
if(!$rVraagOp){
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
}
return mysql_fetch_assoc( $rVraagOp );
}
That should do what you're after.
This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
$sql= "SELECT * FROM $table WHERE $where";
$query= mysql_query($sql);
if ($query != false)
{
$result = array();
while ( $row = mysql_fetch_assoc($query) )
$result[] = $row;
return $result;
}
return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
foreach ($rows as $row)
use($row);
}
This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call. It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
// Holds our mysql resources in a map of "{$table}_{$where}" => resource
static $results = array();
$key = $table . '_' . $where;
if (!isset($results[$key]))
{
// first call of this particular table/where
$results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
}
$row = mysql_fetch_assoc($results[$key]);
if ($row === false)
// remove this key so a subsequent call will start over with a new query
unset($results[$key]);
return $row;
}
// Usage
while ($row = vraagOp("table1", "where field > 7")) {
print_r($row);
}
This
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?
You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.
Your example won’t work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn’t.
How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";
$result_gpfsF=mysql_query($sql_gpfsF);
while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{
call_function();
}
function call_function()
{
echo " Function Called </ br>";
}

Categories