jestkoks
jestkoks

Reputation: 17

if sql value exist php while loop add 1 to variable and execute script

I'm trying to do a loop in php where i have a variable "i" what's value is "1" and if in my database the value of my variable exist it will execute a script and add 1 to my variable and etc. to the time that the value of my variable does not exist in my database. There is my code :

config.php :

<?php
/* Database connection */

$sDbHost = 'localhost';
$sDbName = 'techtronik.pl';
$sDbUser = 'root';
$sDbPwd = '';
$dbcon = mysqli_connect ($sDbHost, $sDbUser, $sDbPwd, $sDbName);
?>

anotherfile.php :

<?php

include('config.php');

$sqlget = "SELECT * FROM pcstacjonarne";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Nie udalo sie polaczyc z baza danych");
$row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC);
$i = 4;
$result = $dbcon->query("SELECT * FROM pcstacjonarne WHERE idpcstacjonarne = '$i'");

while ($result->num_rows == 1) {               
    echo 'Number of post is '.($i++);
}
?> 

But this code don't work i am trying to fix this for 3 hours but i really don't now where is the problem. If someone would help me it will be great.

Upvotes: 1

Views: 528

Answers (2)

Vladimir Despotovic
Vladimir Despotovic

Reputation: 3505

The problem is that you are not making your loop properly. You are using num_rows, which is not what you want exactly. num_rows === 1 is probably never going to happen, so your loop is never happening (maybe only once). Tell us exactly what you want to do, and we can help you out a lot more.

Upvotes: 1

Jason Wright
Jason Wright

Reputation: 59

This problem is solved more easily with a do while, rather than a while:

<?php

include('config.php');
$sqlget = "SELECT * FROM pcstacjonarne";
$sqldata = mysqli_query($dbcon, $sqlget)or die("Nie udalo sie polaczyc z baza danych");
$row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC);

$i = 4;

do {
    $result = $dbcon->query("SELECT * FROM pcstacjonarne WHERE idpcstacjonarne = '$i'");
    if ($result->num_rows === 1) {
        echo 'Number of post is '.($i++);
    }

} while ($result->num_rows === 1);
?>

Upvotes: 1

Related Questions