Hey I'm running php mysqli query:
<?php do { echo $row['depicao']; ?>-<?php } while ($row = mysqli_fetch_array($query)); ?>
The result I need should show the following
data-data2-data3-data4 etc.
However what I'm seeing is:
-data-data2-data3-data4
how can I get the "-" to not appear as the first result?
Ive tried this but I get the same result.
<?php do { echo $row['depicao']; echo'-'; ?><?php } while ($row = mysqli_fetch_array($query)); ?>
Thanks
In
do { echo $row['depicao']; ?>-<?php }
while ($row = mysqli_fetch_array($query))
$row gets defined after first iteration, and not before. That's why
$row['depicao'] outputs nothing. If you had error_reporting on - you would also see a notice.
So, first fix is to define $row first and then output it:
while ($row = mysqli_fetch_array($query)) {
echo $row['depicao'];
echo '-';
}
But in this case your output will be ended with -.
So, one of the solutions is to collect values in array and implode'em:
$values = [];
while ($row = mysqli_fetch_array($query)) {
$values[] = $row['depicao'];
}
echo implode('-', $values);
Use while loop instead of do...while
Because when you use do while loop it'll execute once always and then it'll check the condition and that's why you got the - at very first of your result.
So use while loop to check the condition, if true then code under loop will execute otherwise not.
I'll strictly recommend you to learn about loops.
Try using while loop instead of do-while.
<?php while($row = mysqli_fetch_array($query)) { echo $row['depicao'];echo'-';} ?>
The problem with do while is that it executes at least once even if the condition fails. Hence one "-" is printed in beginning even without evaluating the condition.
If the goal is just to remove the extra "-" then it can be done with-
<?php do { echo $row['depicao']; if($row['depicao']!=null) echo "-"; } while ($row = mysqli_fetch_array($query)); ?>
Related
Been lurking on Stackoverflow for a long time but this is my first post. I am receiving a error related to displaying an array which is supposed to be populated by a mysql query. The echo function just returns ArrayArrayArray instead of what is supposed to be there. The mysql query is comparing a form input (the variable $data) .
<?php
$data = $_POST["search"];
global $data;
// Create Connection
$con = mysqli_connect(xxxxx,xxxxxx,xxxxx,xxxxx);
// Check Connection
if (mysqli_errno($con))
{
echo "Failed To Connect To The Database" ;
}
//Perform Query To Compare And Return Results
$result_array = array();
$query = " SELECT url FROM data WHERE url LIKE '%$data%' " ;
$result = mysqli_query($con, $query);
// While Loop To Return All Comparable Results
while ($row = mysqli_fetch_array($result)) {
$result_array[] = $row['url'];
echo $result_array ;
}
?>
echo will print a string, try using something like print_r() or var_dump() instead
Example
echo '<pre>';
print_r($result_array);
echo '</pre>';
<pre> will allow for easier reading of the array
You can try with following code.
<?php echo '<pre>'; print_r($result_array); echo '</pre>'; ?>
In your code, you want to replace echo $result_array; by echo $row['url']; (to display the content of url at each loop), or remove that line and add a print_r($result_array); after the while{} loop, to display all in one command.
It's also useful use
echo implode(';', $result_array);
for joining strings of each element in $result_array
echo posts the string version of your variable, which in this case will look like Array.
You can use var_dump($result_array); or print_r($result_array); to get the results printed correctly.
I'm a big noob here, so I'm trying to figure it out as a I go.
I want to take a SQL request for "id, fist and last" and store each of those in a variable.
the next half of the code would be doing things with those variable.
The lower statements are simply to see if the var is begin assigned... Apparently it is not, but I get no error, just the blank lines. How can I get the info in a set to do something with?
$newIDs = mysql_query("SELECT per_ID, per_FirstName, per_LastName FROM person_per WHERE DATE_SUB(NOW(),INTERVAL 6 MONTH)<per_FriendDate ORDER BY per_FriendDate DESC") or die(mysql_error());
while($row = mysql_fetch_assoc($newIDs)){
echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName;
echo $row ['per_LastName'] = $per_LastName;
//below is for testing purposes only
echo $per_FirstName;
echo "<br/>";
}
print $per_ID;
echo $per_LastName;
I'm thinking you wanted something more like this for your test:
while ($row = mysql_fetch_assoc($newIDs)) {
$per_ID = $row['per_ID'];
$per_FirstName = $row['per_FirstName'];
$per_LastName = $row['per_LastName'];
// below is for testing purposes only
echo $per_FirstName;
echo "<br/>";
}
When you actually want to keep all the results from your query, you'll need to do something like:
$rows = array();
$i = 0;
while ($row = mysql_fetch_assoc($newIDs)) {
$rows[$i] = $row;
// below is for testing purposes only
echo $rows[$i]['per_LastName'];
echo "<br/>";
$i++;
}
Also, you should note that mysql_fetch_assoc() is actually a deprecated PHP function, according to the manual page: http://php.net/manual/en/function.mysql-fetch-assoc.php
echo $row ['per_ID'] = $per_ID;
should be
$per_ID=$row['per_ID'];
you echo of $per_ID; should then work
As its in a loop you will overwrite $per_ID each time and end up wit the last value.
It looks like your problem is in these statements:
echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName;
echo $row ['per_LastName'] = $per_LastName;
The equals sign there assigns the value of variable $per_ID (which at that time is unassigned) to the array. That's not what you want.
Instead you probably want something like this:
$per_ID = $row ['per_ID'];
Things get further complicated by the fact that you have a while loop in which you would keep writing to the same three variables. So after the loop ends you would only have the value of the last set of fields.
Hey usually I use mysqli_fetch_array to display the content of my database in my CMS, but recently someone told me I should use mysqli_fetch_assoc and push the results into an array so that database only runs once instead of running the database for each record.
But I'm not really sure how to display my fields without showing them all, usually I would echo $data['field_name'], but what I've noticed with mysqli_fetch_assoc is I can't just echo $value['field_name'], all I can do is echo $value and it displays all the results.
This is what I've done, hope that makes sense. Thanks in advance for any help!
PHP
$sql = "SELECT * FROM app_categories";
if($result = query($sql)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i=>$row){
foreach($row as $column=>$value){
echo $value;
}
}
}
why you don't just
echo $row['field_name'];
I'm experimenting with MySQLi and using the following code to check differences for how I should approach my array formatting/usage for fetch_array(MYSQLI_ASSOC);
here is my code:
include "Database.php";
$ArrayQuery = $mysqli->query("SELECT * FROM accountinformation");
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
The problem is, that i'm using the same Variable for my while loop, the first one returns 3 then 3 Which is expected.
But the problem is, with my second query; it returns a blank array
array( ) when print_r();
and when I do:
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
For my Second while loop, it returns nothing for output.
I have checked my variables $ArrayResults and $ArrayResult are not duplicates, they are in fact unique.
Why is my second while loop returning nothing when my first one is working?
Update
When I produce a second query into the mixture with a different starting variable:
$ArrayQuer = $mysqli->query("SELECT * FROM accountinformation");
and modify my second while loop:
while ($ArrayResult = $ArrayQuer->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
I get the expected output? So is it a case of MySQLi not allowing the same parameters to be used twice throughout the script?
mysqli_data_seek
Adjusts the result pointer to an arbitrary row in the
result
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
mysqli_data_seek($ArrayQuery,0); // Addition Made Here
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
To re-use an already fetched array; you should use mysqli_data_seek(); (Notice I have added it above your `$Empty Variable) This should be the problem.
See the manual here:
http://us.php.net/manual/en/mysqli-result.data-seek.php
Think of this scenario; Why would you re-buy something you already own?
Fits perfectly in your case
In a Flex project, I have an array with objects in it. I want to save this array in a cell on a mysql table along with some other basic info like title, and an id.
EDIT: just clarifying since i seem to be getting responses explaining how to echo all the rows... I'm trying to echo the contents of an array that was serialized and placed in a single cell. This array has objects in it.
So, I have this code here to serialize the array, and insert it along with the other info into my DB:
function submitLogDbObj($array,$id,$title)
{
$title=mysql_real_escape_string($title);
return mysql_query("INSERT INTO logs (text,id,title) VALUES ('".serialize($array)."','$id','$title')");
}
Then for a test i'm trying to make a loop that will display the log in a way that looks like a conversation...
an object in my array would look something like:
[1]
icon = ""
msg = "this is a test"
name = "Them: "
systemMsg = 0
[2]
icon = ""
msg = "yep it sure is"
name = "You: "
systemMsg = 0
So here's what i've got so far, but its not working! How can I make a loop that will take that array from the DB, unserialize it and then echo the convo in a way that looks like a chat log?
Thanks!
<?php
include_once("dbinfo.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($result)
{
$log = unserialize($row['text']);
echo 'starting loop!';
echo "<ul>";
/* im not sure how to represent the length of an array in php thats why i just have $log.length */
for ($i = 1; $i <=$log.length; $i++)
{
echo "<div id='logbox'>";
echo "<li>";
$name=$log[$i]['name'];
$msg=$log[$i]['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
echo "<br />";
}
echo "</ul>";
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Well, there're a few things which could be better here:
The length of an array is found through count( $array ) or sizeof( $array )
$value . $otherValue means concatenate those two values. Since length is undefined in this context, $log.length means "$log.length".
The best way to loop through an array is foreach( $set as $val) or foreach( $set as $key => $val )
The preferred method of iterating through a SQL result is the while loop: while($row = mysql_fetch_array($result)){ or do... while (see below). Unless you specifically and consciously only want one, then it would be best to use that. And if you do only want one, then put a Limit in the query.
Serialized arrays in databases has a redundant flavor. Are you sure that this is what you want?
Your serialized array, before it is inserted, should also be run through mysql_real_escape_string.
br really shouldn't be needed if you're surrounding something in its own div.
Indent properly or the kitten of death will come for you.
The improved code:
$row = mysql_fetch_array($result);
// row could be empty if there were no results
if($row)
{
// we've already grabbed the first value, so we need
// to invert while into do... while.
do
{
$log = unserialize($row['text']);
echo "<ul>";
foreach( $log as $line )
{
// Are you sure this should be outside of the li?
echo "<div id='logbox'>";
echo "<li>";
$name=$line['name'];
$msg=$line['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
}
echo "</ul>";
}
while( $row = mysql_fetch_array($result) );
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Firstly, get into the habit of indenting your code properly, it will save you a lot of frustration when looking for errors.
You don't need to know the length of the array, you can just use a while loop: (coding from the hip here so let me know if you get errors)
$result = mysql_query("......") or die("Query failed");
//Keep going while $row isn't FALSE
//mysql_fetch_array returns false when there are no more rows
while($row = mysql_fetch_array($result)){
//You can close PHP tags here and insert the
//variables in the HTML, it often looks neater
//and your editor can colour code HTML, helping
//you to find problems
?>
<div>
<li><?php echo $row['name'] ?></li>
<li><?php echo $row['msg'] ?></li>
</div>
<?php
}
See the "fetch array while loop" of this tutorial for more examples.
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
echo "<ul>";
while ($row = mysql_fetch_assoc($results)) {
$name = $row['name'];
$msg = $row['msg'];
//display data how ever you want
}
echo "</ul>";