I hope someone can help me with this puzzle!
I have this code:
<?php
$user = 'myuser';
$pass = 'mypass';
try{
$dbh = new PDO('mysql:host=localhost;dbname=mybase', $user, $pass);
foreach($dbh->query('SELECT title FROM ads_listing') as $title);
foreach($dbh->query('SELECT slug FROM ads_listing') as $slug){
print_r($slug);
print_r($title);
}
$dbh = null;
} catch (PDOException $e){
print "ERROR!:" . $e->getMessage() . "<br/>";
die();
}
?>
It display:
Array ( [slug] => laptop-dell-e6420-in-good-condition-tj304mkn910a8 [0] => laptop-dell-e6420-in-good-condition-tj304mkn910a8 ) 1Array ( [title] => VW POLO Comfortline [0] => VW POLO Comfortline ) 1Array ( [slug] => vw-polo-comfortline-rf839h9c9d065 [0] => vw-polo-comfortline-rf839h9c9d065 ) 1Array ( [title] => VW POLO Comfortline [0] => VW POLO Comfortline )
The goal is to display from my table 10 random titles as an URL with the slug like: VW POLO Comfortline, Laptop dell e6420 in good condition,.
How can I do it please?
You just need to use LIMIT and RAND() in your query like:
SELECT title, slug FROM ads_listing ORDER BY RAND() LIMIT 10
then use this query and function fetch_assoc() to have the result in associative array type:
<?php
$query = "SELECT title, slug FROM ads_listing ORDER BY RAND() LIMIT 10";
$result = $connection -> query($query);
while($row = $result -> fetch_assoc()){
// you can use $row which has been read from table randomly
...
}
?>
in the previous code, $connection is the connection which has been got from PDO class. Obviously, you do not have to use exactly like what I wrote, but I suggest to you use one.
There are quite a few things going on here from a puristic point of view, but I think there are two things that are preventing you from solving this:
You don't fetch your data in a single query
You don't loop your data in a single loop
Going along with the assumption that $dbh->query() returns an associative array, you could do the following:
$user = 'myuser';
$pass = 'mypass';
try{
$dbh = new PDO('mysql:host=localhost;dbname=mybase', $user, $pass);
} catch (PDOException $e){
print "ERROR!:" . $e->getMessage() . "<br/>";
die();
}
$ads = $dbh->query('SELECT title, slug FROM ads_listing');
foreach ($ads as $ad) {
$title = $ad['title'];
$slug = $ad['slug'];
}
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I have a need to generate a MySQL query dynamically, and values of specific types may or may not appear in specific column types. Here is a case for a query generated for two x values and one y value, each of which must be present in either of respective sets of columns (please to not read it too close, since the query itself has been tested extensively and works alright if the proper parameters are inserted manually):
SELECT
*
FROM
TABLE
WHERE
(
/*start of block x0 */
(
(columm_x0 = ':value_type1_index1')
OR (column_x1 = ':value_type1_index1')
OR (column_x2 = ':value_type1_index1')
OR (column_x3 = ':value_type1_index1')
OR (column_x4 = ':value_type1_index1')
)
/* end of block 0*/
/*start of block x1 */
OR (
(columm_x0 = ':value_type1_index2')
OR (column_x1 = ':value_type1_index2')
OR (column_x2 = ':value_type1_index2')
OR (column_x3 = ':value_type1_index2')
OR (column_x4 = ':value_type1_index2')
)
/*end of block x1*/
/*start of block y1*/
AND (
(columm_y0 = ':value_type2_index1')
OR (column_y1 = ':value_type2_index1')
OR (column_y2 = ':value_type2_index1')
OR (column_y3 = ':value_type2_index1')
OR (column_y4 = ':value_type2_index1')
) /*end of block y1*/
)
This whole query is supplied to $query variable.
So each time we must search for values in all specific columns no matter what. The parameters themselves are supplied as array:
$values = Array ( [type1] => Array ( [0] => value1 [1] => value2 )[type2] => Array ( [0] => value3 ))
My PDO looks like the following:
try {
$connect = new PDO("mysql:host=".$db['server'].";dbname=".$db['db'], $db['mysql_login'], $db['mysql_pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$connect->prepare($query);
foreach ($values as $type => $typevalue){
foreach ($typevalue as $element => $elementvalue){
$parameter = ":value_{$type}_index{$element}";
$stmt->bindValue($parameter, $elementvalue, PDO::PARAM_STR);//i think here is the problem!
echo "<br>$parameter = $elementvalue<br>"; //shows exactly correct parameter and value
}
}
if ($stmt->execute() AND $stmt->rowCount() > 0){
echo "success";
//do some stuff
} else {
echo "false".' '. $stmt->rowCount() . '<br>';
$stmt->debugDumpParams();
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
The resulting query using pdo always returns 0 rows although the parameters replaced with values manually result in success.
As i said above, i don't think that bindValue() method allows variables in parameter.
Any help would be appreciated.
All i had to do was to remove the quotes around the parameters in query so this is correct:
(column_x1 = :value_type1_index2)
and this is NOT correct:
(column_x1 = ':value_type1_index2')
I have situation . I want to insert one array element to another array element but could not find the exact method.
This is my function
public function get_applicants($sort_array = array('apply_id DESC'))
{
global $wpdb;
$sql = 'SELECT * FROM ' . $this->tableac . " ORDER BY " . implode(',', $sort_array);
//$sql = 'SELECT c. * , p. * FROM wp_apply c, wp_apply_files p WHERE c.apply_id = p.apply_id';
$educations = $wpdb->get_results($sql);
$getid=array();
foreach($educations as $education){
//print_r($education);
$sqlfile = 'SELECT * FROM wp_apply_files WHERE apply_id = '.$education->apply_id;
$getalls = $wpdb->get_results($sqlfile);
$allvalues="";
foreach($getalls as $getall){
$allvalues= $getall->uploaded_file.", ";
$getid[]=$getall->uploaded_file;
}
$allvaluesnew=rtrim($allvalues,", ");
// echo "<br>";
// Here I want to insert getid into educations array
}
echo "<pre>";print_r($educations);
die();
//return array($educations,$getid);
}
print_r result show this.
Array
(
[0] => stdClass Object
(
[apply_id] => 44
[choose_position] => HR Manager
[title] => testr
[first_name] => waqas
[last_name] => aamer
[current_job] => developer
print_r get id show like this.
Array
(
[0] => a75d138911c55df639fdd09fade511151-23.pdf
[1] => newone3.pdf
[2] => a75d138911c55df639fdd09fade511151-22.pdf
[3] => newone2.pdf
[4] => a75d138911c55df639fdd09fade511151 (2).pdf
[5] => newone.pdf
)
I want to insert these these elements iteration wise. When in the educations first iteration comes than it should insert all the elements at one index of second array separated by comma.
If I understand your question correctly then following might help.
It will insert comma separated values from $getid into new key called "getid" in $educations array.
public function get_applicants($sort_array = array('apply_id DESC'))
{
global $wpdb;
$sql = 'SELECT * FROM ' . $this->tableac . " ORDER BY " . implode(',', $sort_array);
//$sql = 'SELECT c. * , p. * FROM wp_apply c, wp_apply_files p WHERE c.apply_id = p.apply_id';
$educations = $wpdb->get_results($sql);
$getid=array();
foreach($educations as $key => $education){
//print_r($education);
$sqlfile = 'SELECT * FROM wp_apply_files WHERE apply_id = '.$education->apply_id;
$getalls = $wpdb->get_results($sqlfile);
foreach($getalls as $getall){
$getid[]=$getall->uploaded_file;
}
// echo "<br>";
// Here I want to insert getid into educations array
$educations[$key]["getid"] = implode(",", $getid);
}
echo "<pre>";print_r($educations);
die();
//return array($educations,$getid);
}
Hope this helps and this is what you want
I'm building an array of rows from a DB using the code below.
$site = new stdClass();
$dbh = _vic_commander_db();
$sth = $dbh->prepare('SELECT name, title, url FROM site ORDER BY siteid');
$sth->bindColumn(1, $site->name);
$sth->bindColumn(2, $site->title);
$sth->bindColumn(4, $site->url);
$sth->execute();
$ret = array();
while ($sth->fetch(PDO::FETCH_BOUND))
{
$ret[] = $site;
}
The array ($ret[]) does get added to each iteration of the loop; however in addition to APPENDING each of the rows of the table, all elements get REPLACED by the last result appended. So I have an array with the same number of elements as rows in the table but the elements are all the same.
Any ideas would be much appreciated.
Example out:
array(3) (
[0] => stdClass object {
name => (string) Same Site Name
title => (string) Same Site Title
url => (string) samepurl.com
}
[1] => stdClass object {
name => (string) Same Site Name
title => (string) Same Site Title
url => (string) samepurl.com
}
[2] => stdClass object {
name => (string) Same Site Name
title => (string) Same Site Title
url => (string) samepurl.com
}
)
All the array indexes point to the same object $site.
You have to copy by value instead of by reference:
$ret[] = clone $site;
see http://php.net/manual/en/language.oop5.cloning.php
Also I wonder why you really need to store an object here.
The other answer has a decent explanation, but why not just fetch into an array of objects?
$sth = $dbh->prepare('SELECT name, title, url FROM site ORDER BY siteid');
$ret = $sth->fetchAll(PDO::FETCH_OBJ);
try this way, according to documentation ( execute() before bindColumn() ):
$site = new stdClass();
$dbh = _vic_commander_db();
$sth = $dbh->prepare('SELECT name, title, url FROM site ORDER BY siteid');
$sth->execute();
$sth->bindColumn(1, $site->name);
$sth->bindColumn(2, $site->title);
$sth->bindColumn(4, $site->url); //could you explain why 4?? not 3 ???
$ret = array();
while ($sth->fetch(PDO::FETCH_BOUND))
{
$ret[] = $site;
}
I'm building a php notification system (kinda like facebook's).
It works as should, listing all events the way i want it. but i'm trying to get it to understand that if it gets 3+ events on the same post, it will join these events into one notification.
Now it looks like this:
User 1 wrote on article-x
User 2 wrote on article-x
user 3 wrote on article-x
user 1 wrote on article-y
instead i want it to be printed like this :
user 1 and 2 others wrote on article-x
Been trying to read up on what i need to do this, but no luck. any pointers greatly appreciated.
It's being queried like this:
edited with full code
$sesname = $_SESSION['user_name'];
$sesid = $_SESSION['full_name'];
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$stmt = $dbh->prepare("select * from comments WHERE full_name = '$sesid' and checked ='1' ");
$stmt->bindParam(':full_name', $safe_name, PDO::PARAM_INT, 5);
$stmt->execute();
$result = $stmt -> fetchAll();
foreach( $result as $row ) {
$name = $row['name'];
$pid = $row['pid'];
$commentid = $row['id'];
$fullink = $row['fullink'];
$datetime = $row['dt'];
if ($name == $sesname){
} else {
echo "<div id='commentnote'><a href='http://{$fullink}'>{$name}</a>kommenterte ditt <a href='{$fullink}'>blogginnlegg</a><br><div class='updentry' style='color: red ! important; cursor: pointer; margin-top: -35px; position: absolute; right: 8px;'>x</div></div>";
}
}
Tried using your answers underneath, but without luck. Thanks for answering though, i really appreciate it :)
What about turning the article into a multidimensional array? (Just an example, structure isn't optimal since I don't know what data you have and need.)
if(count($post['comments']) >= 3) {
echo $post['user'][0] ."and". (count($post['comments'])-1). " others wrote on ..";
} else {
//Just one
}
Maybe you could create a 2-dimensional array like this:
Array
(
[article-x] => Array
(
[0] => User1
[1] => User2
)
[article-y] => Array
(
[0] => User1
)
)
If you want to do this in PHP, do something like this:
$events = array();
foreach( $result as $row ) {
if( isset($events[$row['article']) ){
$events[$row['article']]['counter']++;
}else{
$row['counter'] = 0;
$events[$row['article']] = $row;
}
}
foreach( $events as $event ){
echo "<div id='commentnote'>{$event['user']}".($event['counter']?' and '.$event['counter'].' others':'')." wrote on {$event['article']}</div>";
}
Here is my simplified code:
$connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD);
$connexion2 = new PDO(SQL_DSN2,SQL_USERNAME2,SQL_PASSWORD2);
[...]
$sqlIndex = "SELECT index_key,index_platforms_code
FROM index
WHERE index_missions_id = :mission";
$initFiches = $connexion->prepare($sqlIndex);
$initFiches->bindParam(":mission" , $_GET['mission']);
$initFiches->execute();
try
{
while ($fiche = $initFiches->fetch(PDO::FETCH_ASSOC))
{
print_r($fiche);
foreach ($structure['champs'] as $masterChamp)
{
//$stmt = $connexion2->prepare($masterChamp['sql']);
}
}
}
catch (exception $e)
{
echo "error".$e->getMessage();
}
My output:
Array
(
[index_key] => 1
[index_platforms_code] => 1
)
Array
(
[index_key] => 2
[index_platforms_code] => 2
)
Array
(
[index_key] => 3
[index_platforms_code] => 3
)
Array
(
[index_key] => 4
[index_platforms_code] => 4
)
All Right, but if I uncomment this line
$stmt = $connexion2->prepare($masterChamp['sql']);
in the foreach, this line broke the while above and here is the new output:
Array
(
[index_key] => 1
[index_platforms_code] => 1
)
Someone have an idea?
Here's a solution that doesn't involve 2 connections and that's more optimized.
$connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD);
$sqlIndex = "SELECT index_key,index_platforms_code
FROM index
WHERE index_missions_id = :mission";
$initFiches = $connexion->prepare($sqlIndex);
$initFiches->bindParam(":mission" , $_GET['mission'], PDO::PARAM_STR);
$initFiches->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $connexion->prepare("SELECT ...."); // Prepare outside of the loop, you don't have to prepare it X times, once is enough.
if(sizeof($data))
{
foreach($data as $row)
{
// Do your statement binding / executing.
}
}
Alternatively, it seems you might be able to do this with table joining rather than issuing a query for each row you get from the 1st table. Since you haven't posted the structure, I guess there's no much helping it at the moment.