Exists any alternative more beautiful at this loop? - php

$i=0;
while ($row=mysql_fetch_assoc()) {
if ($i==0) echo "First"
$i++;
}
Access directly to mysqli pointer? a php class like's Iterator?
Thanks.

I’d use this:
if ($row = mysql_fetch_assoc()) {
// process first item
while ($row = mysql_fetch_assoc()) {
// process following items
}
}

$first = true;
while ($row=mysql_fetch_assoc()) {
if ($first) echo "First"
$first = false;
}

If you're trying to use the first element for something special, then maybe something like:
$row=mysql_fetch_assoc();
//do stuff to first row
do {
//do stuff to all rows (including the first)
} while ($row=mysql_fetch_assoc());
Otherwise I have no idea what the question is and I'm not a PHP guy...

Do not have any method for know exactly position in all moment?
for example java iterator implements next or hasNext(), if !hasNext() the item is the last.

well, if i understand your question correctly, you want the first row and then iterate through the others:
$row = mysql_fetch_assoc(); // $row contains first row
while ($row = mysql_fetch_assoc()) { // loop through the rest of the rows
}

Related

how to check, if there are still rows left from fetch_assoc loop?

I loop trough the rows with this code:
while ($row = $result->fetch_assoc()) {
//...
}
But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()
Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.
$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
if(++$loop_ct < $row_cnt) {
//do something
}
}
I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:
$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
//....
$cnt--;
if($cnt == x){ //Where x is the number you want
//....
}
}
You're doing a while loop until you don't have any rows left, so the question is do you really need a test or do you just run the code you want at the end of your loop? If you need to test inside whether there will be a next row, you could do this:
$row = $result->fetch_assoc();
while (1) {
...
if (!$row = $result->fetch_assoc()) {
// No next row
break;
}
}
Which is pretty similar to what you're doing now.
Consider the code you posted
while ($row = $result->fetch_assoc()) {
//...
}
It is already doing that. check out the docs for mysqli_result::fetch_assoc, the while loop will break if $result->fetch_assoc() returns NULL. You don't need to manually check anything.
Either you can go with #McWayWeb or you can try this function mysqli_next_result().
Read it's manual here:- http://php.net/manual/en/mysqli.next-result.php

check duplicated data from selected data

Hello i'm going to check duplicated data from selected data but my code is not working properly
the my code is:
$cs="0";
$location=array();
$check=array(); $check[0]="";
while ($db_field = mysql_fetch_array($result)) {
for ($z=0; $z<=$cs;$z++){
if($check[$z]==$db_field['location']) {
//*in here going to check same or not
}
else {
//*if not same $location_c[$cs] will get
$location_c[$cs]= $db_field['location'];
$check[$cs]= $db_field['location'];
}
}
$cs++;
}
this code prints all data not checking duplicated data.
I think you should use in_array() to avoid duplication, I've also removed unnecessary things :
$location=array();
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['location'], $location_c)) {
$location_c[] = $db_field['location'];
}
}
assuming the duplicate is the location field
$cs="0";
$location=array();
$check=array();
while ($db_field = mysql_fetch_array($result)) {
for ($z=0; $z<=$cs;$z++){
if (in_array($db_field['location'], $check)) continue;
$check[]=$db_field['location'];
$location_c[$cs]= $db_field['location'];
}
$cs++;
}
but can't you avoid duplicates with your SQL query?
The first issue you have is in your for statement: for ($z=0; $z<=$cs;$z++). There is no need for this. You should use in_array() in order to determine, if what your looking for has been set. Also, there is no need to use incremental values for your key. If you use [] there is no overhead, and will automatically use number keys.
Lastly, it appears that there is no reason to use a $check array at all. You can go straight to $location_c. This cuts down a lot of code:
$location_c = array();
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['location'],$location_c)){
$location_c[]= $db_field['location'];
}
}

How to Retrieve 1 Result from Custom MySQL fetch Function

Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.

Saving 2 variable's values for later use

I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);

Easy method to print something, only once inside while loop?

I want to fetch information from one table and loop that until it's done, with the help of a while loop. Although, I want one column to be printed only once inside the loop.
There's two solutions I've come up with...
<?php
$i = 0;
// while loop start
if($i == 0){
// stuff to print
$i++;
}
// while loop end
?>
And ofcourse, I could just make another query before the while loop.
But these methods really aren't too efficient. Is there a less messy way to do this?
Actually, I'd be okay with running another query before the while loop, if it didn't get so messy, and perhaps if I could just re-use the query intended for the loop (I fetch everything from the table). I tried experimenting with mysql_fetch_field, but I'm not sure I get how it works, or if that even helps here * embarrassed *
Currently, the code looks like so:
$fetch = mysql_query("SELECT *
FROM `pms`
JOIN `pm_conversations` ON pms.ConvID = pm_conversations.ID
WHERE `ConvID`='".$_GET['id']."'");
$i = 0;
while($print = mysql_fetch_array($fetch)){
if($i == 0){
echo $print['Subject'];
$i++;
}
<table>
<th><?=$print['From']?>, <?=$print['DateSent']?></th>
<tr><td><?=$print['Message']?></td></tr>
</table>
}
If I understand your question correctly, I think you've got the right idea. I'm guessing you want to print something extra the first iteration (like maybe column headers using the array keys)?
$cnt= 0;
while($row = mysql_fetch_assoc($res)) {
if(0 == $cnt++) {
// first iteration only
}
// all iterations
}
Or, if I'm totally off a better description of what you're trying to do and the real world situation would help.
Have you thought about do...while? It has all of the benefits of while, plus it allows for code to conditionally happen before the first iteration.
$res = mysql_fetch_array( $resource );
// run the magical run once query/functionality/bunnies/whatever
// Hey, I'm tired. Let there be bunnies.
do
{
// put the regular while loop constructs in here;
}
while( $res = mysql_fetch_array( $resource ) );
$rs = mysql_query("SELECT * FROM tbl");
$row = mysql_fetch_array($rs);
do {
echo $row['column_name'];
} while($row = mysql_fetch_array($rs));
I don't know if this is what you need. Hope this one helps. =]

Categories