While statement skips fist row - php

I think that because of the if statement, the while statment skips the first one.
But i need the IF and i need the WHILE.
here is my code:
if($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
$antwoorden .= "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
}
}

It looks like your if statement is just checking to see if there are results from the query. If that's true and you really want to keep the if statement, you could update it to use mysqli_num_rows() instead:
if(mysqli_num_rows($results_antwoorden_select) > 0) {
while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
$antwoorden .= "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
}
}
Note: mysqli_fetch_array() will return null if there aren't any results, so technically just eliminating the if block entirely will let your sample code work perfectly fine.
Alternatively, if you really want to keep the mysqli_fetch_array() in the if block, you could update your loop to be a do/while instead:
if($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)) {
do {
$antwoorden .= "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
} while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select));
}

You're using $row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select) in your if statement which is absolutely wrong because you must check available number of rows in your table using num_rows function You should try this will resolve your issue
if($results_antwoorden_select->num_rows > 0){
while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
$antwoorden = "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
}
}

Related

MySQL: Num Rows not working

I've stumbled upon a simple MySQL error, and it seems my attempts of fixing it are effortless. The problem, it's not counting.
Before I go further, I know that mysql_* is Deprecated, and that I shouldn't use it. I should use mysqli_* or PDO.
This is my Query, and yes, the echo is just for testing.
$ms_sql = mysql_query("SELECT * FROM mijnsp WHERE sp_username = '".$user['username']."'");
while ($mijnspusers = mysql_fetch_assoc($ms_sql)) {
$ms_count = mysql_num_rows($ms_sql);
if($ms_count <= 0){
echo "Result is empty";
}else{
echo $mijnspusers['new_username'];
}
I've tried to change the IF, but with no effect;
if($ms_count <= "0"){
or, like this
if($ms_count <= '0'){
Thank you in advance,
Pascal
Call
$ms_count = mysql_num_rows($ms_sql);
before the while() loop.
You should do the mysql_num_rows() before going into the loop. If the num is 0, then you'll never run the loop to begin with.
Your code should be:
$ms_sql = mysql_query("SELECT * FROM mijnsp WHERE sp_username = '".$user['username']."'");
$ms_count = mysql_num_rows($ms_sql);
if($ms_count == 0){
echo "Result is empty";
}else{
while ($mijnspusers = mysql_fetch_assoc($ms_sql)) {
echo $mijnspusers['new_username'];
}
}`

Show different image depending on value in variable

just want to make sure I'm going in the right direction with this. I have an image which I want to be replaced/changed if the value of a variable is either 0/1. So here is the code from the guy doing the server side stuff.
<?php
//Requires mysql_connect to create the connection
$link_state = 0;
//If you so wish you don't have to check for a connection, but may be a good idea leave this in.
if ($mysql_connection['connected'] == true) {
$result = mysql_query("SELECT * FROM link");
//The bit we are looking for should be the first row, and we should only get one row
$count = mysql_num_rows($result);
if ($count <= 0) {
//Interesting...
$mysql_error['error'] = true;
$mysql_error['description'] = "ERROR: No rows were returned from table 'link'";
} else {
//We should be ok to continue
if ($count > 1) {
$mysql_error['error'] = true;
$mysql_error['description'] = "WARNING: Found more than one row in 'link' table!";
}
$row = mysql_fetch_array($result);
$link_state = intval($row['state']);
}
} else {
$mysql_error['error'] = true;
$mysql_error['description'] = "ERROR: No mysql connection!";
}
/*
After the completion of this page, $link_state will be one of two things:
* 0 = offline
* 1 = online
Throws to $mysql_error:
1 Warning
2 Errors
*/
?>
Okay, so I'm assuming by that little bit of code I will then have a value of either 0 or 1 in $link_state.
So from this can I then just do a simple inline script like this to get my relevant image?
<img src="img/<?=($link_state=="0"?"off.jpg":($link_state=="1"?"on.jpg":))?>" />
Any insight would be great :)
Thanks in advance.
try this
<?php $img = ($link_state == "0") ? "off.jpg" : "on.jpg"; ?>
<img src="./img/<?php echo $img; ?>" />
also use mysqli_* since mysql_* is depreciated.

odbc query returns the first row twice then returns the rest normally

I am querying a database with an odbc connection through php. When I query the db it returns the first row twice and then the rest of the rows the correct amount of times.
Example query:
$stm = SELECT[sUsername] FROM [dbo].[Abilis].[Users] WHERE sUsername = ?;
$pstm = odbc_prepare($conn, $stm);
$exc = odbc_execute($query, array($Username));
I have also tried using DISTINCT but that has not worked either.
EDIT:
for($i=0; $i<odbc_num_rows($pstm);$i++){
$row = odbc_fetch_array($pstm, $i);
if($row['OnCreditHold'] == '1'){
$out = '<button style="color:red;margin:0 auto;" class="btn" onclick="'.'window.location.href='."'information.php?info=".$row['Account_no'];
$out .= "'".'">'.$row['Name'].'</br>';
$out .= $row['Del_ad1'].'</button>';
}
else{
$out = '<button class="btn" style="margin: 0 auto;" onclick="'.'window.location.href='."'information.php?info=".$row['Account_no'];
$out .= "'".'">'.$row['Name'].'</br>';
$out .= $row['Del_ad1'].'</button>';
}
echo $out;
}
You have checked the query result is good outside of this app -- good for you. That means the problem is your loop structure, or maybe your method of getting the data such as odbc_fetch_array().
I ran into this problem once, and I can't recall the solution. I had to try alternative methods to isolate the cause.
For example, instead of for (), try foreach ($elems as $elem) { ... }.
Of course, simplify all the other aspects while you are trouble-shooting. For example, remove the if() structure.
The use of the function odbc_fetch_array ($pstm, $i) with the second parameter starting with zero causes the problem. When you use 0, and the second time 1, it will give you the same result. You could use a while-loop instead of a for-loop and don't use the second parameter.
while ($row = odbc_fetch_array($result))
{
// do something
}

how to echo the line one time under the while loop

I have a code like this
<?php
$getLeftSide = 'select * from leftmenu';
$result = $db -> query ($getLeftSide) or die ("$db->error");
if ($result) {
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
}
?>
I need to echo this line one time
echo "<div class='left_main_cat'>Web and Design</div>";
of course it's under the while loop so it print it self many times
is there is a why to solve this and print this line one time only.
As Ben suggests, the easiest and clearest solution is to use a boolean check variable:
$catFound = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
// We only want this category printed for the first category,
// if it exists.
if(!$catFound) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
$catFound = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Although it seems better to use a boolean variable and a comment to make clear your intent.
Ugly, but I'm not that good at PHP yet!
$has_printed = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
if(!$has_printed){
echo "<div class='left_main_cat'>Web and Desigen</div>";
$has_printed = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Simple solution: Add another boolean variable with default value false Then just check if false, print your text and set it true.
adding a boolean or check variable or any kind of conditional inside of a loop is a very bad idea imho, i NEVER do it. every time you swing through the loop, the condition has to be checked. it's like a badly written switch/case.
figure out a way to do it before the loop.
unroll the loops, most people do it to save space but most compilers will unroll them anyway for optimization
stick it before the loop
find a java or css way to hide it until the loop is done or you want to display stuff.

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories