I have following code:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
trafficsource.id AS trafficsourse_id,
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
WHERE advertiserId = '$advertiser_id'";
$mysqli = new mysqli();
$mysqli->connect('localhost', 'root', '', 'adsbase');
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo "<h2>Traffic Sources: {$row['trafficsource']}</h2>";
}
This code show results like:
Traffic Sources: Example1
Traffic Sources: Example2
Traffic Sources: Example2
Traffic Sources: Example1
Traffic Sources: Example2
Traffic Sources: Example1
What I want and can't figure out is to show results like:
Traffic Sources: Example1, Example2
So without duplicates and also all in one line.
You nearly had it:
$result = $mysqli->query($query);
$trafficeSources = array();
while ($row = $result->fetch_assoc()) {
$trafficSources[] = $row['trafficsource'];
}
echo '<h2>Traffic Sources: ' . implode(', ', $trafficSources) . '</h2>';
EDIT: Query using DISTINCT
I'm assuming you only need the traffic source name, but feel free to add more columns back in if they're required. Bear in mind though that the DISTINCT applies to a distinct combination of all rows returned, so it may be possible that you could end up with duplicate traffic sources if other selected columns differ.
$query = "SELECT DISTINCT trafficsource.name AS trafficsource
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
WHERE advertiserId = '$advertiser_id'";
Try this small solution:
$trafic = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($trafic)) $trafic[] = $row['trafficsource']
}
if(!empty($trafic)){
echo '<h2>Traffic Sources:' . imlode(',', $trafic) .'</h2>';
}
$trafficSources = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['trafficsource'], $trafficSources) {
$trafficSources[] = $row['trafficsource'];
}
}
echo "<h2>Traffic Sources: ".implode(', ', $trafficSources)."</h2>";
Use Group by in 'trafficsource' in query and then in while loop concat each value of $row['trafficsource'] to other and echo it outside the while loop.
Related
getChildIds can be very slow if running it against a large set of resources, so I am trying to write a query and some code to get all the child ids faster.
However I am getting different results from getChildIds & my script.
Can anyone see why these would be yielding different results?
Method using getChildIDs:
$parentDepth = isset($scriptProperties['parentDepth']) ? $scriptProperties['parentDepth'] : 5;
$parents = explode(',', $parents);
$children = array();
foreach ($parents as $parent){
$ids = $modx->getChildIds($parent,10,array('context' => 'web'));
foreach($ids as $id){
$children[] = $id;
}
}
echo ' number of children = ' . count($children);
method using queriees & a loop:
$comma_separated = implode(",", $parents);
$sql = "SELECT `id` from modx_site_content where `parent` IN (".$comma_separated.") and published = 1 and isfolder = 0 and deleted = 0 and hidemenu = 0;";
$results = $modx->query($sql);
$mychildren = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$mychildren[] = $row['id'];
}
for($i=0; $i <= 10; $i++){
$comma_separated = implode(",", $mychildren);
$sql = "SELECT `id` from modx_site_content where `parent` IN (".$comma_separated.") and published = 1 and isfolder = 0 and deleted = 0 and hidemenu = 0;";
$results = $modx->query($sql);
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$mychildren[] = $row['id'];
}
}
echo ' number of children = ' . count($mychildren);
The getChildIDs method takes nearly 1.5 seconds to run and gives about 1100 results
The SQL/script method runs un under 0.1 second and gives 1700 results.
Either I'm not appending the child ids to the array properly ~or~ maybe getChildIDs is filtering out some other results?
does anyone have any clues as to what could be happening here?
You can try to use built-in method of pdoFetch.
$pdo = $modx->getService('pdoFetch');
$ids = $pdo->getChildIds('modResource', 0);
print_r($ids);
It also recursive, but can be better in some situations.
Of course, you need to install pdoTools from the repository first.
Looking at the code again, the discrepancy in results is pretty obvious now. I'm appending results to the child id array, it's inserting duplicates since one parent can have many children.
the solution to avoid duplicates:
$mychildren[$row['id']] = $row['id'];
getChildIds - is recursive, so it slower by default.
If the 'SELECT' statement is used to select data from a database then how do we echo specific rows to specific places on a page using php?
To explain this better - I am trying to SELECT * ALL FROM a table but to echo multiple rows to particular places on the html page using php.
So, imagine that my entire mark up and css has 20 thumbnails on a page and each thumbnail has data and an image that is unique to each thumbnail....do I have to replicate the below 20 times?
I am thinking that the best way to do this (which is probably completely wrong) is to use this statement
SELECT * FROM name_of_table WHERE ID = 4 >>> i.e. where I'd like that specific data echoed....
So, if I have 20 thumbnails do I do this 20 times?
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID = 4;")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
Print "<th>Product:</th> <td>".$info['product_name'] . " </td></tr>";
}
Print "</table>";
?>
And, rinse and repeat but I change the below statement each time for each thumbnail (each thumbnail has unique data that comes from each row on the MySQL)
SELECT * FROM name_of_table WHERE ID = 4;
What is the best way of doing this?
Thanks!
Simple example.. First get the data with wanted ID:s. Create function for data request.
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID IN (2,3,4,5,6);")
or die(mysql_error());
// This holds all data rows
$data_array = array();
while($info = mysql_fetch_array( $data ))
$data_array[] = $data;
// Function for rendering data to html
function getItemHtml($id) {
$html = "";
foreach($data_array as $row) {
if ($row['ID'] == $id) {
$html = "<td>" . $row['title'] . "</td>";
// etc.. create item html here
break;
}
}
return $html;
}
// To create one item just call this with item id.
echo getItemHtml(4);
?>
I have one database with two tables: "music" and "agenda".
But for some reason once I have queried one table, I cannot perform a similar query on the other table. Or in any case, its variables are empty.
I'd think I could just keep the connection open and perform a second query after the first "while". Like so:
<?php
mysql_connect('localhost', 'root', 'root');
mysql_select_db('erikverwey');
$result = mysql_query("SELECT * FROM agenda ORDER BY date DESC LIMIT 0, 2") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$count++;
$date[$count] = $row['date'];
$time[$count] = $row['time'];
$place[$count] = $row['place'];
$venue[$count] = $row['venue'];
$who[$count] = $row['who'];
$concert[$count] = $row['concert'];
$urlvenue[$count] = $row['urlvenue'];
}
$result2 = mysql_query("SELECT * FROM music ORDER BY id LIMIT 0, 5") or die(mysql_error());
while($row = mysql_fetch_array($result2)) {
$count++;
$song[$count] = $row['song'];
$artist[$count] = $row['artist'];
$duration[$count] = $row['duration'];
$url[$count] = $row['url'];
}
mysql_close();
?>
But no. In this case, all the variables from the table "music" remain empty.
I've been looking for an answer, but no luck. I'm still new to MySQL, though, so apologies beforehand if this is standard stuff. Thanks!
I found the glitch. Because the counter "$count" was used a second time, it started where it left off and couldn't find any data.
Use a different counter, also in the variables (!), and all is good.
I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.
I have this script
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But in the .xls file it prints only one user. Why id doesnt print all of the users ? W
Thanks in advance.
I make the change you said with $sheet
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$sheet->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But it still prints out only one record. And yes when i run the query in phpmyadmin it returns more than one record.
How can i print out data from mySql table.. What is going wrong ?
I am pretty sure it is because you are using a unique identifier (WHERE tmima_id='6'). It is only finding the results for that one unique identifier and displaying that. Hope this helps.
$i is being reset to row 3 every loop. Set $i=3; before the while loop, not inside it.