Why is my array coming out like this? - php

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

Related

merge two columns into an array

I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm

PHP SQL statement using REGEXP to fetch multiple values

How do I use REGEXP to fetch multiple data from the array $vall.
I referred a sample code from:
PHP sql statement where clause to multiple array values
Some of the sample data: CGCG-0025-0,CGCR-0003-0,CGRQ-0163-0
foreach ($list as $value) // this $list is from another array
{
$part = $value[3];
$vall[] = $value[3]; // $list1 is an empty array
}
$partnumber =[];
foreach($vall as $v)
{
$partnumber[] = "*.".$v.".*";
print_r(array_values($partnumber)); // these are some of the values Array ( [0] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* [2] => *.CGCR-0003-0.* )
}
foreach($partnumber as $x)
{
echo '<br>'.$partnumber; // shows 'Array' on each lines
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
//example 1 $fsql="select * from MPdError where RptDatime = 201706091000 and partnumber = ('CGRQ-0057-0') ";
//example 1 shows the correct data but i need multiple partnumber
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo '<br><br><br>ID:'.$id.'<br>Machine Number :'.$mac;
}
Though this may not be a good solution as it contains a huge security risk, I will still post it based on what is needed above.
REGEXP is not needed for data that are not complex in design.
$fsql = "select * from Error where RptDatime = 201706091000 and partnumber in ('" . implode("','", $vall) . "');"

delimit PHP/PDO execute result on multiple unrelated tables

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,

php getting values out of an array with same 'id' number

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.

PHP MYSQL multidimensional array

I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!

Categories