I have a mysql query:
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
echo '
<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'
';
}
This query will generally select between 2 and 5 different rows and display them in a list.
I want the first echoed line to only appear once and the second line should appear between 2 and 5 depending on the data in my db.
I am sure there is a simple way to do this, I've tried GROUP BY mag but this will eliminate the remaining 1-4 pieces of data I wish to display.
Not sure I understand your question, as the following solution seems too simple!
$row = mysql_fetch_array($result);
echo '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'';
while ($row = mysql_fetch_array($result)) {
echo ''.$row['title'].'';
}
May be this is a solution to your problem ?
$lines = '';
unset($hgroup);
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
if (!isset($hgroup)) {
$hgroup = '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>';
}
$lines += '
'.$row['title'].'
';
}
echo $hgroup.$lines;
Related
How do i str_split each character result output from mysqli database i have tried:
require("init.php");
$result = mysqli_query($conn, "SELECT item_name , quantity FROM books WHERE book = 1905515");
if($row = mysqli_fetch_assoc($result))
{
$da = $row["item_name"];
$qty = $row["quantity"];
}
$sql = mysqli_query($conn, "SELECT name , recharge , details , logo , price FROM promo WHERE code='$da' LIMIT 1");
if($rrow = mysqli_fetch_assoc($sql))
{
$code = $rrow["recharge"];
$see = str_split($code, 2);
echo "<br/>$see"; // not working fine, outputs 'Array'
echo "$code"; // working fine
}
all i get as result is 'arrary' thanks for your time and impact
A few directions here, I will give a few examples.
1) If you are simply wanting to echo out each row column, with a break, then all you need is this:
if($rrow = mysqli_fetch_assoc($sql))
{
echo '<br>' . $rrow['recharge'];
}
2) If you do need to split the 'recharge' column into 2-character array values, and then output those again as a solid string, you could do this:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
echo '<br>' . implode('',$codebits);
}
3) And if you needed to put each 2-character split on its own html row, you can add that to the implode like this:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
echo implode('<br>',$codebits);
}
4) However, how or what you are wanting to do with the code from 'recharge', is flexible at this point. Various ways we can go with it, and since its in an array, you can even wrap each array element in more html as you need:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
foreach($codebits as $codebit) {
echo '<div class="something">'. $codebit .'<span>more html</span></div>';
}
}
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'];
}
I have a polymer(1.0) app i am trying to create (based on stretch-tutorials league table), i cant figure out the routing if use mvc, so i have opted for the one page site, referencing different php files.
I Have a table in MYSql that i trying to incorporate into the table, using a simple echo table script, but this repeats itself hundreds of times. How can i stop this loop ?
$result = mysql_query('select * from results',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$sql = ('SELECT `home_team_name`,`away_team_name`,`home_goals_for`, `away_goals_for`, DATE_FORMAT(`fixture_date`, "%e %M %Y"), TIME_FORMAT(`fixture_time`, "%h:%i %p") FROM `results` ORDER BY fixture_date desc LIMIT 20 '.$table) or die('cannot show columns from '.$table);
echo '<h3>',$table,'</h3>';
$result2 = mysql_query($sql);
if(mysql_num_rows($result2)) {
echo '<table cellpadding="4" cellspacing="0" class="table table-striped table-hover table-bordered">';
echo '<tr class="info"><th>Home team</th><th>Away Team</th><th>Score</th><th>Score</th><th>Date<th>Time</th></tr>';
while($row2 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row2 as $key=>$value) {
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
I have added ' < 50 ' but this returns 50 table header rows only ?
the site is live at http://jay-o.uk/#!/results the css and other data are okay for now, just this pesky loop.
Well.. maybe you need this code:
// Create an array
$items = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
/* print new insert */
var_dump('new item');
/* add a new item */
$items[] = array(
'home_team_name' => $row['home_team_name'],
'away_team_name' => $row['away_team_name'],
'home_goals_for' => $row['home_goals_for'],
'away_goals_for' => $row['away_goals_for']
);
}
$json_response = json_encode($items);
print $json_response;
If $json_response are a empty array maybe the problem is that the query don't return any row.
You need to set a "LIMIT" in the first query if you want to avoid a timeout operation, also i think that is posible to call a unique query that return all the info that you need but i don't know because your query is unintelligible.
Your code is wrong, the second query don't use the $table variable that is null value and what is de purpose to putting it after the limit parameter?
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 50');
if(mysql_num_rows($results)) {
print '<table>';
while ($row = mysql_fetch_row($results)) {
print '<tr>';
foreach ($row as $field_name => $field_value) print '<td>'.$field_value.'</td>';
print '</tr>'
}
print '</table>';
}
Sorry, the code is a bit messy, ive been working on this for a while and ifs frustrating, im not sure where i am going wrong, if i remove the $tableName variable i get an empty array, no matter what i do this is the results.
I have tried in json to no avail...
$db = mysql_connect($host,$user,$pass);
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db($db_name,$db);
$resulting = mysql_query("select * from results", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
$row_array['home_team_name'] = $row['home_team_name'];
$row_array['away_team_name'] = $row['away_team_name'];
$row_array['home_goals_for'] = $row['home_goals_for'];
$row_array['away_goals_for'] = $row['away_goals_for'];
//push the values in the array
array_push($json_response,$row_array);
$json = json_encode($json_response);
//echo $json;
$json_result = print_r((array) json_decode($json,true));
echo $json_result;
}
which leaves this: jay-o.uk/config/config.php
Could this be because i am referring to a view in mySql rather than a table ?
How about a simpler solution, just limit the query from the database to 1:
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 1');
This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 months ago.
Should be pretty basic, but I can't get it to work. I have this code to iterate over a mysqli query:
while($row = mysqli_fetch_array($result)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
It works and returns:
Variable #1: (Array, 3 elements) ↵
0 (String): "4testtest" (9 characters)
1 (String): "1Hello world!Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!" (99 characters)
2 (String): "2Sample PageThis is an example page. It's different from a blog post because it will stay in one place and will show up in
your site navigation (in most themes)." (161 characters)
The problem is that it puts all three colums into one column, so I can't access them seperatly.
This for example:
0 (String): "4testtest" (9 characters)
Should be seperated into 4, test, test
When I do this:
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row['post_id'];
$posts['post_title'] = $row['post_title'];
$posts['type'] = $row['type'];
$posts['author'] = $row['author'];
}
It only outputs 1 row instead of all three …
Any help is greatly appreciated!
Get all the values from MySQL:
$post = array();
while($row = mysqli_fetch_array($result))
{
$posts[] = $row;
}
Then, to get each value:
<?php
foreach ($posts as $row)
{
foreach ($row as $element)
{
echo $element."<br>";
}
}
?>
To echo the values. Or get each element from the $post variable
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
-ID Title
-1 Gary
-2 John
-3 Michaels
Both will works perfectly in mysqli_fetch_array in while loops
while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
(OR)
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
mysqli_fetch_array() - has second argument $resulttype.
MYSQLI_ASSOC: Fetch associative array
MYSQLI_NUM: Fetch numeric array
MYSQLI_BOTH: Fetch both associative and numeric array.
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
Try this...
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
I want to make a php search query.
First put a sentence and explode every word get $name.
Then I put $name make a query to match all the name which exist in my database.
How to use a if ($num_results > 0) if I am not sure how many $name are matched and echo out?
(may be $row['name'] is null, maybe $row['name'] is 1 or 2, I want to get them one by one)
$query = mysql_query("SELECT * FROM books
WHERE name LIKE '$name[0]' OR name LIKE '$name[1]' OR name LIKE '$name[2]'
OR name like '$name[3]' ");
while ($row = mysql_fetch_array($query)) {
if ($num_results > 0) {
echo $row['name'][0] ;
}
if ($num_results > 1) {
echo $row['name'][1] ;
}
if ($num_results > 2) {
echo $row['name'][2] ;
}
if ($num_results > 3) {
echo $row['name'][3] ;
}
}
use:
mysql_num_rows($query);
to get the amount of rows you get from your mysql query
<?php if (mysql_num_rows($query)>0){?>
Do stuff
<? }else{ ?>
We didn't find anything!
<?php }?>
How about:
$i = 0
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
I didn't actually understood what you really want but your code should make more sense like this:
<?php
$searchphrase="alex nick george";
// this:
$names = explode(" ",$searchphrase);
// produces the following:
$names = array("alex","nick","george");
// so you can make the query:
if(is_array($names)){
$query = "SELECT * FROM books WHERE name IN ('".implode(",",$names)."') ORDER BY FIELD (name,".implode(",",$names).")";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0){
// no results
}else{
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
}
}
}
?>
Perhaps if you describe it better we can help more efficiently.