Show multiple results from PDO::FETCH_ASSOC - php

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.

Related

Create array in PHP from mysql

I think that I may be over trying things with little sleep but I am having problems creating arrays from mysql queries. I have a query like so:
$result = mysqli_query($con,"SELECT * FROM vehicles ORDER BY id");
while($row = mysqli_fetch_array($result)) {
$description = $row['description'];
$description = strtoupper($description);
$id = $row['id'];
}
I want it to create an array like so:
$v[1] = "Myarray1";
I have tried this but it does not work:
$v[ $row['id']] = $row;
Do I have to query like this:
while( $row = mysql_fetch_assoc( $result)){}
and if I do, how I do create the array as I need it?
Many thanks in advance
At no point are you creating an array here. In your loop you are simply modifying some variables that in the context you posted I cannot reason on.
If all you need, no data filtering whatsoever this will do:
$list = Array();
while( $row = mysqli_fetch_array($result) ) {
$list[] = $row;
}
[] basically 'appends' in PHP, it is an ugly mechanism but it works.
If you want to access rows per primary key ( id in your case I think ) then simply replace [] with [$row["id"]]
I'm not exactly sure of the end result you're looking for. But if you want to access the results as $row['column'], where 'column' is a column name in your MySQL database, then you need to use mysql_fetch_assoc. I think this example will help:
while (($row = mysqli_fetch_assoc($result))) {
$v[$row['id']] = $row;
}
$v[1]['description'] is the data in the column description for the record with an id=1

PHP automatically create variables based on what is in mysql database

I dont know if this is possible, but am trying to create a php variable using an entry from a mysql database.
For example, lets say I want to create the following variables, but i want to replace google with whatever the company name is in the database.
$google = $row['companyname'];
$google_ticker = $row['ticker'];
$google_holding = $row['holding'];
So if I had a row in my database with the company name as Yahoo, the following would appear instead:
$yahoo = $row['companyname'];
$yahoo_ticker = $row['ticker'];
$yahoo_holding = $row['holding'];
I have tried different variations of the following however I cant get it to work (I know the code below wont work, its just an example of the sort of thing I have tried):
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$$row['companyname'] = $row['companyname'];
$$row['companyname']_ticker = $row['ticker'];
$$row['companyname']_holding = $row['holding'];
}
I can get it to work using something similar to the following, however doing it this way means I have to create each variable manually (as far as i know). I am trying to get it to create my variables automatically depending on what company names I have in my database.
$values = [];
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$values[$row['companyname']] = $row;
}
$google = $values['google']['companyname'];
$google_ticker = $values['google']['ticker'];
$google_holding = $values['google']['holding'];
Any ideas on how I can achieve this?
Many Thanks
Use a (multidimensional-)Array with KEYS that function as variable names:
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$data[$row['companyname']]['name'] = $row['companyname'];
$data[$row['companyname']]['ticker'] = $row['ticker'];
$data[$row['companyname']]['holding'] = $row['holding'];
}
Now you can access the holding variable like this:
echo $data['google']['holding'];
That should get you started...
Succes!
You can use like this:
${$row['companyname']} = $row['companyname'];
doc

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

How can I get and display all values of a certain field in a sql table?

I have a table wherein I need to get all the data in one column/field, but I can't seem to make it work with the code I have below:
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
$row = mysqli_fetch_array($result111);
echo $row['name'];
With the code above, it only prints one statement, which happens to be the first value in the table. I have 11 more data in the table and they are not printed with this.
You need to loop through the recordsets .. (A while loop will do) Something like this will help
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
The mysqli_fetch_array() function will return the next element from the array, and it will return false when you have ran out of records. This is how you can use while loops to loop through the data, like so:
while ($record = mysqli_fetch_array($result)) {
// do something with the data...
echo $record['column_name'];
}

Mysql database retrieve multiple rows

I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.
my current code:
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution=$row['solution'];
}
?>
The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.
You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.
A very simple way (obviously I haven't included mysql_num_rows etc):
$solutions = array()
while($row = mysql_fetch_assoc($result)) {
$solutions[] = $row['solution'];
}
If you have three in your result solutions will be:
$solutions[0] -> first result
$solutions[1] -> second
$solutions[2] -> third
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$solution = array();
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution[]=$row['solution'];
}
?>

Categories