Merge arrays in php - mysql

In the above code in each foreach loop i get a seperate array every time . I wanna combine all these array . I have tried array_merge but it is not working . Is there any other way?
Some of the results are two dimentional array
foreach ($location as $loc)
{
$query = "select name
from locations l where l.location_id = $loc";
$query = $this->db->query($query);
$data = $query->result_array();
}
Thanks in advance.

Either use array_merge():
$data = array();
foreach ($location as $loc) {
$query = "SELECT name FROM locations l WHERE l.location_id = " . $loc;
$query = $this->db->query($query);
$data = array_merge($data, $query->result_array());
}
...or merge the location id's first and then do a single query, which is much faster:
$in = implode(', ', $location);
$query = "SELECT name FROM locations l WHERE l.location_id IN (" . $in . ")";
$query = $this->db->query($query);
$data = $query->result_array();

$q = 'SELECT `name` FROM `locations` AS `l` WHERE ';
foreach ($location as $loc) {
$q .= "`l`.`location_id` = '$loc' OR ";
}
$q = rtrim($q, 'OR ');
$query = $this->db->query($q);
$data = $query->result_array();

Related

PDO query returns multiple arrays. How to uniquely identify them?

This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.

Mysql - Get data from two tables

I have two tables webadstats and webstatsclick and i want to make below query from these two tables.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
COUNT(B.click) as 'clickss'
FROM `webadstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubadhash = B.pubadhash
WHERE A.pubadhash='$pubadhash'
GROUP BY date(from_unixtime(A.time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$impressions[] = $row['impressions'];
$clicksall[] = $row['clickss'];
$timestamp[] = $row['timestamp'];
}
for($i=0; $i<count($clicksall); $i++){
$str .= $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i] ."\n";
}
}
echo $str;
But the problem is that this query is generating same values for both the variables impressions and clickss out of which value of impressions variable is correct.
1542434400||1270||1270
1542520800||1800||1800
1542607200||1745||1745
1542693600||1805||1805
1542780000||1615||1615
1542866400||1740||1740
1542952800||1740||1740
1543039200||1830||1830
1543125600||1830||1830
1543212000||1615||1615
1543298400||1880||1880
1543384800||2125||2125
1543471200||1530||1530
1543557600||1370||1370
1543644000||120||120
My both the DB structure is
webadstats db
webadstats db
webstatsclick db
webstatsclick db
Kindly help me where i am wrong.
Let's go back to the two query approach. The problem is, we've been trying to use JOIN on pubadhash but also WHERE with pubadhash, so the values get multiplied.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webadstats`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$sql3 = "SELECT
count(*) as 'clickss',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webstatsclick`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$arr[$row['timestamp']]['impressions'] = $row['impressions'];
$arr[$row['timestamp']]['timestamp'] = $row['timestamp'];
$arr[$row['timestamp']]['clickss'] = 0;
}
$result3 = mysqli_query($conn, $sql3);
if (mysqli_num_rows($result3)>0) {
while($row = mysqli_fetch_assoc($result3)) {
$arr[$row['timestamp']]['clickss'] = $row['clickss'];
}
}
foreach($arr as $clicks){
$str .= $clicks['timestamp'] . '||' . $clicks['impressions'] . '||' . $clicks['clickss'] ."\n";
}
}
echo $str;

How can I get mysql result as a array

Here I have a translator that must get data from mysql and then show them like a $_name = array ($_en, $_ru, $_ua) and then I want to choose data by cases [0] or [1] or [3]
I need to show mysql result an array
I've already try this it but it doesn't work
<?php
$result1 = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result1)) {
t_name = array ('t_ru', 't_ua', 't_en' )
}
?>
$result = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result))
$t_names[] = $row;
Try
$result1 = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result1)) {
$t_names[] = array ('t_ru'=>$row['t_ru'],'t_ua'=> $row['t_ua'],'t_en'=>$row['t_en'] );
}
or
while ($row = mysql_fetch_array($result1)) {
$t_names[] = $row;
}
now data available on $t_names
I tried it but I have to get also $t_name from mysql and then have it like an array
$result1 = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result1)) {
('t_name'=>$row['t_name'] )= array ('t_ru'=>$row['t_ru'],'t_ua'=>
$row['t_ua'],'t_en'=>$row['t_en'] );
};
?>

PDO Double LIKE with Params

I'm executing a query with PDO that doesn't retrieve any result via PHP but works in phpMyAdmin.
I'm sure about the connections setting as it's not the first query of my script and the other ones work fine.
Here the PHP code :
$retour = array();
$filters = array();
$filters['media_type'] = 'mytype';
$filters['libelle'] = 'sometext';
$start = 0;
$count = 9;
$sql = "SELECT * FROM ".DB_PROD_PREFIX.$this->table." t ";
$sql .= " LEFT JOIN ".DB_PROD_PREFIX.$this->table."_lang l ON t.id = l.id AND l.langue = :langue";
$sql .= " WHERE 1";
if (count($filter)>0){
foreach($filter as $field => $value){
$sql .= " AND ".$field." LIKE :".$field;
}
}
$sql .= ($order!='' ? " ORDER BY ".$order : '');
$sql .= ($count != '' ? " LIMIT ".($start != ''?':start':'0').", :count" : '');
$stmt = $db->prepare($sql);
if($start != '') $stmt->bindParam('start', $start, PDO::PARAM_INT);
if($count != '') $stmt->bindParam('count', $count, PDO::PARAM_INT);
if ($langue != '') $stmt->bindParam('langue', $langue);
if (count($filter)>0){
foreach($filter as $field => $value) {
$f = '%'.$value.'%';
$stmt->bindParam($field, $f, PDO::PARAM_STR);
}
}
echo $stmt->queryString.print_r($filter, true);
if (!$stmt->execute()) echo $stmt->errorInfo();
$res = $stmt->fetchAll();
foreach($res as $id => $row){
$retour[]=$row;
}
return $retour;
If I unset one of the 2 keys of $filter array, the query work fine.
Here is the SQL generated :
SELECT * FROM table1 t
LEFT JOIN table1_lang l ON t.id = l.id AND l.langue = :langue
WHERE 1
AND media_type LIKE :media_type
AND libelle LIKE :libelle
ORDER BY position LIMIT :start, :count
Thanks for your help!
Pierre M.
It doesn't work better but thanks for the tip!
Here is a piece of code managing the LIKE parameters that works :
$media_type = '%'.$filter['media_type'].'%';
$stmt->bindParam('media_type', $media_type, PDO::PARAM_STR);
$libelle = '%'.$filter['libelle'].'%';
$stmt->bindParam('libelle', $libelle, PDO::PARAM_STR);
Why doing the same with a foreach on the array doesn't work ?
if (count($filter)>0){
foreach($filter as $field => $value) {
$value = "%$value%";
$stmt->bindParam($field, $value, PDO::PARAM_STR);
}
}

MySql LIKE returns false if search term is same as entire string in the column, why is that?

So I have following as part of my query
SELECT * FROM $table WHERE columname LIKE '%$searchterm%'
I have tried taking out leading and/or ending wildcards meaning
SELECT * FROM $table WHERE columname LIKE '$searchterm%'
AND
SELECT * FROM $table WHERE columname LIKE '%$searchterm'
AND
SELECT * FROM $table WHERE columname LIKE '%$searchterm%' OR columname LIKE '$searchterm'
and also tried adding following to the query with no luck
OR columname = '$searchterm'
So when my search term is "myval" and if column has whole string "myval", I would like to have that selected. But ALL of my queries above, return false/return nothing where myval is searchterm and column value as full.
I can not use MATCH because this is not Full-Text index.
EDIT:
PHP Code:
$sterm = NULL;
$table = 'mytable';
if(isset($_GET['s'])) { $sterm = explode(" ", mysql_real_escape_string($_GET['s'])); }
if(isset($_POST['s'])) { $sterm = explode(" ", mysql_real_escape_string($_POST['s'])); }
if(!empty($sterm)){
$getdata = "SELECT * FROM $table WHERE termsi != 'Special' ";
foreach ($sterm as $value){
$getdata .= "AND netid_all LIKE '%$value%' OR netid_all = '$value' ";
} //End foreach
$getdata .= "LIMIT 10";
$result = mysql_query($getdata) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo <<<PRINTALL
{$row[0]}, {$row[1]}, {$row[2]}, {$row[3]}, {$row[4]}, {$row[5]}, {$row[6]}, {$row[7]}, ' <br />'
PRINTALL;
} //End While
} //End If search exists
Okay So As you guys suggested, i tried PHPMyAdmin sql console and it works fine, so it would have to be by PHP!? so here it is.
I'd suggest writing your query building like this:
$fullvalues = array();
$partials = array();
foreach ($sterm as $value){
$partials[] = "(netid_all LIKE '%" . mysql_real_escape_string($value) . "%')";
$fullvalues[] = "'" . mysql_real_escape_string($value) . "'";
}
$partials = implode(' OR ', $partials);
$fullvalues = implode(', ', $fullvalues);
$sql = <<<EOL
SELECT *
FROM $table
WHERE (termsi != 'Special')
AND (($partials) OR (netid_all IN ($fullvalues));
EOL;
Assuming your search string is a b c, you'd get this query:
SELECT *
FROM yourtable
WHERE (termsi != 'Special')
AND (((netid_all LIKE '%a%') OR (netid_all LIKE '%b%') OR (netid_all LIKE '%C%')) OR (netid_all IN ('a', 'b', 'c')))
If your search requires that all terms be present, then change the 'OR' to 'AND' in the implode.
Well found it,
$row = mysql_fetch_array($result, MYSQL_ASSOC);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
Was the problem, earlier when I was testing things, anyhow, it should have been the following
$row = mysql_fetch_array($result, MYSQL_ASSOC);
while($row)