Multiple records with GET and PDO - php

Trying to figure out how to do this on multiple records. I am trying things out, looking at reference but not understanding how to get it working, firstly here Here is my code that works:
My href link in loop.
city
My PHP
if (isset($_GET['city'])) {
$city = $_GET['city'];
$stmt = $db->prepare("SELECT * from table WHERE city = ? ");
$stmt->execute(array($city));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) : //loop starts
} else { //html content }
The above simply pulls city records that are being called via a URL variable in my first loop. What If wanted to repeat this multiple times with different URL Variables to generate different results from the database. So instead of just getting one record like my above code I want to get 2 more, here is a below example of what I mean.
Example Href links in a loop with the URL variables city, name country:
city
name
country
Example of PHP which is not working, but getting these URL variables and passing them through to mysql by SELECT, hopefully you get what I mean):
if (isset($_GET['city'], $_GET['name'], $_GET['country'])) {
$city = $_GET['city'];
$name = $_GET['name'];
$country = $_GET['country'];
$stmt = $db->prepare("SELECT * from table WHERE city = ? OR name = ? OR country = ?");
$stmt->execute(array($city, $name, $country));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) : //loop starts
} else { //html content }
Any advice on how to achieve this would be appreciated, also if there is an easier way to do this or my current code is not up to scratch, please let me know. Thanks!

if (isset($_GET['city'])||isset($_GET['name'])||isset($_GET['country'])) {
echo $city= $_GET['city'];
echo $name=$_GET['name'];
echo $country $_GET['country'];
}

I think you're looking to put the url's into an array so that you can use them later? If so, you could do something like this:
if (isset($_GET['city'], $_GET['name'], $_GET['country'])) {
$city = $_GET['city'];
$name = $_GET['name'];
$country = $_GET['country'];
//added:
$url_array = array();
$stmt = $db->prepare("SELECT * from table WHERE city = ? OR name = ? OR country = ?");
$stmt->execute(array($city, $name, $country));
//$row changed to $rows
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)) : //loop starts
//foreach added
foreach($rows as $row){
$url_array[] = $row;
}
} else { //html content }
I hope that helps?

Related

PHP: update variables on while statements

I am new to the PHP world! Currently practicing MySQL and PHP alone
I want to update my <p> content when my query is completed. But seems like my $name only shows the previous value:
$query = $_GET['query'];
$stmt = $conn->prepare("SELECT * FROM wordList WHERE word = '$query'");
$name = ''; // my variable
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$name == $row['word']; // not working
}
And I am not getting the actual data I want in my HTML:
<p>My name is: <?php echo $name; ?></p>
But getting:
My name is:
Thanks
Try using only one equal to symbol = instead of ==.
$name = $row['word'];

MYSQL SELECT statement with variable based on PHP loop

for ($i=1;$i<5;$i++) //Loop read & save all vars from fieldform
{
if (array_key_exists('country'.$i, $_POST) == true)
{
${"country".$i} = $_POST['country'.$i];
$get_id = mysqli_query($connection, "SELECT country_id FROM country WHERE country_pl = '{$country[$i]}'");
$row = mysqli_fetch_assoc($get_id);
$country_id = $row['country_id'];
echo $country_id;
}
}
This is a loop for read & save country name selected in form field. Everything works fine, beside MYSQL QUERY. I don't know how to write '{$country[$i]}' properly in a MySQL statement.
Don't use variable variables, use an array.
$country[$i] = mysqli_real_escape_string($connection, $_POST['country'.$i]);
Then you can do:
$get_id = mysqlil_query($connection, "SELECT country_id FROM country WHERE country_pl = '{$country[$i]}'");
It's better to run one query instead of one every iteration. I would suggest:
$countries = array();
for ($i=1;$i<5;$i++) //Loop read & save all vars from fieldform
{
if (array_key_exists('country'.$i, $_POST))
{
$countries[] = mysqli_real_escape_string($connection, $_POST['country'.$i]);
}
}
$get_id = mysqli_query($connection, "SELECT country_id FROM country WHERE country_pl IN ('" . implode ("', '", $countries) . "')");
while ($row = mysqli_fetch_assoc($get_id)) {
$country_id = $row['country_id'];
echo $country_id;
}
Ideally you should use a prepared statement, but that's a bit more tricky: see Trouble binding an imploded array into a mysql prepared statement

PDO expecting all results to show up but only one shows

I'm trying to execute a statement where it will show all of the results for each row of my table but all it is doing is showing the results from the last row.
<?php
require_once('php/dbconfig.php');
$stmt = $DB_con->prepare("SELECT * FROM users");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = array($row['user_name']);
$email = array($row['user_email']);
}
echo $name[0];
?>
This will work but it will only echo out the name of the last person in my table. If I try to replace the 0 with any other number nothing will show.
I would like to be able to show all users and emails in a list.
In the following block you are assigning each name to the variable $name.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = array($row['user_name']);
$email = array($row['user_email']);
}
I think you intend to either echo $name each iteration of the loop by adding the echo to the loop as:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = $row['user_name'];
$email = $row['user_email'];
echo "{$name} - {$email}";
}
or to add it to an array of names by changing the assignment from $name to $name[] which means 'the next index of the $name array'.
Fetch also returns one record, so you'll need to loop the results or change to fetchAll as suggested by other answers.

Show multiple results from PDO::FETCH_ASSOC

Iwas wondering if someone could help me?
I have a table called markers, in this table it stores multiple records each with a name etc. I would like to echo each name however the below code only shows one results. How can I show more than one. Can someone please help I am new to PDO.
$stmt = $dtb->query('SELECT * FROM markers');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName = $row['name'];
}
Use an array to hold the result, in your code, the variable $markerName is overwrote on each iteration.
$stmt = $dtb->query('SELECT * FROM markers');
$markerName = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
That is because you are overwriting it each and every time , use an array instead.
Rewrite like this...
$markerName = array(); //<---- Add here
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
echo implode('<br>',$markerName); //<---- Implode it up for display
Rewrite like this
$names = $dtb->query('SELECT * FROM markers')->fetchAll();
Being new to PDO, you are supposed to try tag wiki first, where you can find an answer not only to this one but to many other questions.

php array selection

I have the following code and want to manually select an array:
<?php
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
while($article= mysql_fetch_array($articleQuery )){
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
}
echo $aid[0];
?>
The problem is that its not really selecting/displaying the correct information. What I want is to be able to select the value of the first array.
Thanks in advance.
$firstrow = null;
while($article= mysql_fetch_array($articleQuery)) {
if ($firstrow === null)
$firstrow = $article;
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
//manipulate $aid, $media and $link.
}
//manipulate $firstrow
If you only need the first row, limit the query to one result and execute mysql_fetch_array at most once, instead of in a loop.
Or you can do like this:
$array = array();
while($article = mysql_fetch_object($articleQuery )){
$array[] = $article;
}
echo $array[0]->id; // get first id
echo $array[0]->media; // get first media
echo $array[0]->link; // get first link
echo $array[1]->id; // get second id
echo $array[1]->media; // get second media
echo $array[1]->link; // get second link
// and so on.......
if you want $aid to be an array, you should do something like that:
$aid = array();
while($article= mysql_fetch_array($articleQuery )){
$aid[] = $article['id'];
}
The problem is that its not really
selecting/displaying the correct
information. What I want is to be able
to select the value of the first
array.
What you want is propably this:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
$article= mysql_fetch_array($articleQuery);
echo $article[0];
You have unnecessary loop. You can also add "limit 1" to sql query. Although I'm not sure I understand your goal correctly.
Using mysql_fetch_assoc, will use the field names as the array indexer, so $article['id'] instead of $article[0]. That way if you change the definition of the table by adding new columns, your code won't break!
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1");
$article= mysql_fetch_assoc($articleQuery);
var_dump($article);
If you really only want the first result:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1"); // note LIMIT clause
if( false !== ($article = mysql_fetch_array($articleQuery )))
{
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
}
echo $aid;
If you want them all, but indexable:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
while($article= mysql_fetch_array($articleQuery ))
{
$aid[] = $article['id'];
$media[] = $article['media'];
$link[] = $article['link'];
}
echo $aid[0];
Why not edit your SQL statement to select only one item?
mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1");
But the error in your code, is that you're looping over all your selected records, overwriting your variables on each pass. If you want to store all the rows as an array, you should modify your syntax like this:
while($article= mysql_fetch_array($articleQuery )){
$aid[] = $article['id'];
$media[] = $article['media'];
$link[] = $article['link'];
}
...after which you could access the first row with aid[0].
But instead I'd suggest a different structure:
while($article= mysql_fetch_array($articleQuery )){
$articles[]['aid'] = $article['id'];
$articles[]['media'] = $article['media'];
$articles[]['link'] = $article['link'];
}
What that does, is collect all the data into a single data structure, where each record holds all the data related to the article. You would access it like this:
echo $articles[0]['aid'];
echo $articles[0]['media'];
echo $articles[0]['link'];
If this looks like hebrew to you, take a look at the PHP manual section for arrays.

Categories