Have a PHP factory with a sub class that queries either one or more unrelated tables in a database. The class takes a table name as a parameter and returns an array object.
When more than one table is required, I would like a way to delimit each tables result set in to its own array. The class would then return a multi-dim array.
I would prefer to not instantiate another instance of the factory. Here is the current query/result code block. I've left out all the other non-essential code for brevity
// if array has more than one table to query,
// run queries on each table
$count = count($tname);
if ($count>1) {
foreach ($tname as $value) { //each table name in array
/* $query = "SELECT s.* FROM $value s"; tried with table alias */
$query = "SELECT * FROM $value";
if ($stmt = self::$_conn->prepare($query)) {
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
} else {
return false;
}
}
return $result;
// else if only one table to query
} else {
$string = $tname; //table name
$query = "SELECT * FROM $string";
if ($stmt = self::$_conn->prepare($query)) {
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
} else {
return false;
}
}
With more than one table, would return something like:
Array
(
[0] => Array
(
[team_id] => 3
[team_name] => Maverics
)
[1] => Array
(
[team_id] => 4
[team_name] => Stallions
)
[3] => Array
(
[fld_id] => 1
[fld_name] => 6v6-1
)
[4] => Array
(
[fld_id] => 2
[fld_name] => 8v8-2
)
)
Where 0,1 are from one table and 3,4 are from another.
Thank you in advance
Figured it out... Simple actually, just didn't see it before I asked the questions. I changed:
$result[] = $row;
to
$result[$value][] = $row; //line 11 in code block example
This now returns the array with each table name as the array name for the result set.
Thanks anyway,
Related
I have a table as below in SQLite3 (the list could be much longer.):
id cid uname date
1 33788127 6155ce36e45b4 20210930 104822
2 56198567 6155ce387f0cd 20210930 104824
3 27255356 6155ce399e1ca 20210930 104825
4 59519951 6155ce3a7ae0d 20210930 104826
I'd like to get all cids from the table.
Currently, I'm using the below function to get the cid list:
function getCidList () {
$db = new SQLite3($this->db_file);
$table = $this->table;
$sql2 ="SELECT cid FROM $table";
$results = $db->query($sql2);
$res = [];
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
array_push($res, $row['cid']);
}
$db->close();
return $res;
}
Result:
Array
(
[0] => 33788127
[1] => 56198567
[2] => 27255356
[3] => 59519951
)
My question is: Is this the best way to get the intended result? (I feel like looping might not be the most efficient way when the list becomes longer, but I have not been able to find alternative ways). Is there an easier way to get the cid list other than using the while loop?
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
array_push($res, $row['cid']);
}
Thanks!
I am querying the DB successfully using an array and I am getting the correct result. But I am having difficulty using the results because of the way the array is created.
Here is the OUTPUT:
Array (
[0] => Array (
[0] => Array (
[0] => 1#1.1
)
[1] => 2#2.2
)
[2] => 3#3.3
)
Here is how the code is generated:
$owners_string = $row['profile_id'];
$owners_stringd = unserialize($owners_string);
foreach ($owners_stringd as $profileid => $valuee) {
if ($valuee) {
$sql = "select email from {$mysql_tbl_pre}profile where profile_id = '$valuee' ";
$err = mysqli_query($estate_db, $sql);
if (!$err)
error_dlg(mysqli_error($estate_db));
elseif (mysqli_num_rows($err) <= 0)
info_dlg("Error");
while ($row = mysqli_fetch_array($err))
$new_array[$profileid] = $row['email'];
$new_array = array($new_array);
foreach ($new_array as $emailvalue)
$emailsd = print_r($emailvalue, true);
} else {
$emailsd = "";
}
}
I know how to implode the results, but when i do implode this result, is comes out as "Array, 1#1.1" (which ever email was last).
I need it to be one entire result such as 1#1.1,2#2.2,3#3.3
These are two separate Tables. The first Tables stores a string of Ids that, the second Tables has each Id in its own row with an email in a separate column.
Solution from the while loop:
while ($thisemail = mysqli_fetch_array($rsz)) {
$emailsd .= $thisemail['email'] . ',';
}
foreach ($emailsd as $emailvalue)
$email = print_r($emailvalue, true);
I'm having trouble getting the value out of an array
Array
(
[0] => id
[column_name] => id
)
Array
(
[0] => businessType
[column_name] => businessType
)
Array
(
[0] => name
[column_name] => name
)
Array
(
[0] => city
[column_name] => city
)
...
I'm getting those values from
mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
")
And in my while loop
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_array($colName)){
if($row[$i] == 1){
//here comes the missing part
}
$i++;
}
}
I tried diffrent things, but according to print_r, the values I need to get have the same number of id (0). Is there any way, I can get the values out of this array.
I found that I should do it with foreach, but somehow everything I try it fails.
There is no need to use 2 while loops.
The $row array is an associative array, so you can use...
$columns = array();
// {query}
while($row = mysql_fetch_array($result)) {
$columns[] = $row['column_name'];
}
var_dump($columns);
Your $columns array now contains an index of all the columns. It's a zero-index, so these can be pulled individually using:
echo $columns[0]; // The first column from the query "id"
echo $columns[2]; // The third column from the query "name"
You can also loop this array as needed.
foreach ($columns as $id => $column) {
if ($id == 0) {
// Do something with the first column:
echo $column;
} elseif ($id == 2) {
// Do something with the third column:
echo $column;
}
}
try this
$res = mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
");
while($r = mysql_fetch_row($res)){
$arr[]=$r;
}
NOTE . do not use mysql. Try mysqli or PDO instead.
And with this:
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_assoc($colName)){
if(($column['0'] == $row[$i]) && ($row[$i] == 1)){
//something like this???
}
}
$i++;
}
Your question is a bit messy XD.....i hope this helps anyway.
I need to produce an array that is formatted as follows:
Array(
Array([100000116287110]=>
Array([name] => Bryce [image] => abcd.png))
Array([100003019827186]=>
Array([name] => Ross [image] => defg.png))
)
The data to produce the array comes from 2 different sources and is fed to a function.
The function call is lookupUserData($a, array(“name”, “image”)) //this has been set up so other details from the user table can be called simply by adding the field name in the array.
$a is formated as $a = “100000116287110,100003019827186”
The current code I am using for the function is as follows:
function lookupUserData($f,$u)
{
$f = explode(",",$f); //user id from string – converts string to array ([0] =>100000116287110 [1] =>100003019827186)
$u = implode(",",$u); //fields to extract – converts array(“name”,”image”) to name,image
$r=array(); //define results array`
$nr = count($f); //count number of ids to process
for($i=0; $i<$nr; $i++) { //process each id in $f array
$r[]=$f[$i];
$res = mysql_query("SELECT {$u} FROM users where id ={$f[$i]}"); //query user table
$val= mysql_fetch_assoc($res); //return requested fields ($u) from user table
array_push($r, $val); //add values to array $r
}
print_r ($r); //check array output – testing only
return $r; //return array for processing
}
This however returns the result as follows:
Array(
Array([0]=>[100000116287110]
Array([name] => Bryce [image] => abcd.png))
Array([1]=>[100003019827186]
Array([name] => Ross [image] => defg.png))
)
I know I have missed something simple but just cannot seem to get this right!
Something like this:
$r= array();
for($i=0; $i<$nr; $i++) { //process each id in $f array
$res = mysql_query("SELECT {$u} FROM users where id ={$f[$i]}"); //query user table
$val= mysql_fetch_assoc($res); //return requested fields ($u) from user table
$r[$f[$i]] = $val;
}
I have got data from mysql_fetch_assoc stored in to an array using this command
if(mysql_num_rows($data) > 1){
while($row = mysql_fetch_assoc($data)){
$ndata[] = $row;
}
} else {
$ndata = mysql_fetch_assoc($data);
}
Now when I use count on $ndata, it retuns 1; although it is empty.
When I run mysql_num_rows on the returned data it retuns 0 rows. But when I convert the data to $ndata and then run count on that it returns 1. I want it to return the number of rows.
Thanks
Can someone please explain why is there a problem and how to fix it?
Your logic is wrong: you don't test for the case that mysql_num_rows($data) == 0. If this is the case, your code executes the same path as when the number of rows is 1 ($ndata = mysql_fetch_assoc($data);). But there are no more rows to return (there are no rows at all), so mysql_fetch_assoc returns false. And count(false) returns 1, because that's how count works.
Do it this way:
$rows = mysql_num_rows($data);
if($rows == 0) {
return null;
}
else if($rows == 1){
$ndata = mysql_fetch_assoc($data);
} else {
while($row = mysql_fetch_assoc($data)){
$ndata[] = $row;
}
}
You can either return null or array() in the first if branch; these are the only two values for which count returns 0.
I think mysql_fetch_assoc() is returning false (see doc) and count(false) returns 1.
$data = mysql_query($query);
while($row = mysql_fetch_assoc($data)){
$ndata[] = $row;
}
if(count($ndata) == 1) $ndata = $ndata[0];
Runing query that returns 1 row and
$data = mysql_query("SELECT * FROM online LIMIT 1");
print_r($ndata);
Result
Array ( [timestamp] => 1301826108 [ip] => 213.186.122.2)
Runing query with multiple rows...
$data = mysql_query("SELECT * FROM online");
print_r($ndata);
Result
Array
(
[0] => Array
(
[timestamp] => 1301848228
[ip] => 67.195.112.29
)
[1] => Array
(
[timestamp] => 1301826108
[ip] => 213.186.122.2
)
[2] => Array
(
[timestamp] => 1301825465
[ip] => 77.88.28.246
)
[3] => Array
(
[timestamp] => 1301763579
[ip] => 69.171.224.251
)
)
It seems I finally got what you need (However, question remains extremely vague and it's hard to tell for sure). But anyway.
$ndata = array();
while($row = mysql_fetch_assoc($data)){
$ndata[] = $row;
}
Now you would get desired result from count($ndata). It will return 0 for no rows, 1 for 1 row and whatever number if more rows returned. Bingo!
But if you're still planning to get different kinds of arrays, I should warn you against doing it this way.
Always state explicitly what kind of result you want to get:
$ndata = array();
if ($type=="row"){
$ndata = mysql_fetch_assoc($data);
} elseif ($type=="array"){
while($row = mysql_fetch_assoc($data)){
$ndata[] = $row;
}
}