PHP while loop not proceeding in the 2nd while loop - php

I'm trying to fetch row so i can print it on my table. But the problem is that, the code only runs on the 1st while loop. After it fetch all the rows in the table, it stops there.
`Assuming that I have 5 rows in my tblUnit
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
echo " <script type'text/javascript'> alert('1');</script>";
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel from tblFloors where floorID = $floorNumber");
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while ($u = $t->fetch(PDO::FETCH_ASSOC)) {
echo " <script type'text/javascript'> alert('2');</script>";
$floorLevel = $u['floorLevel'];
while ($x = $w->fetch(PDO::FETCH_ASSOC)) {
echo " <script type'text/javascript'> alert('3');</script>";
....
...
..
}
}
}
The output(In alert box):
1
1
1
1
1
I'm using MS SQL Server for my database.

Could be a string evalueting problem try thsi way
$t = $db->query("select floorLevel from tblFloors where floorID = " . $floorNumber .";");
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = " . $unitType . ";");
or
$t = $db->query("select floorLevel from tblFloors where floorID = '$floorNumber' ;");
Otherwise your $floorNumber don't contain the aspected result

Related

Repeating SQL insert statement in loop till id has certain value?

<?php
include ("db.php");
$id2 = "SELECT MAX(id) FROM osalejad;";
$id = $conn->query($id2);
if (id<= 8){
while($id<= 7) {
$min = 1;
$max = 20;
$suvanumber = rand($min, $max);
$bar = (string) $suvanumber;
$prii= "vaba2" . $bar;
$sql="INSERT INTO osalejad (name) VALUES ('$prii')";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
else {
echo '8 osalejat on juba kirjas';
}
?>
I have a question, i want to insert data into MYSQl table, word with a random number, but problem is, it never work as it should - if i have 3 records in name column, then till, it adds 8 more records, instead of 5 records. Is something outside of scope atm?
I will use the DB in this code.
<?php
include("db.php");
$sql = "SELECT * FROM `osalejad`;";
$result = $conn->query($sql);
$var = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = mysqli_fetch_array($result)) {
$var[] = $row["name"];
}
} else {
/// echo "0 results";
}
//shuffle the array, and encode into json.
shuffle($var);
$brack=json_encode($var);
$testbrack= json_encode(array_chunk($var,2));
$final = '{';
$final .= '"teams":';
$final .= $testbrack;
$final .= ',"results":[[[[0,0],[null,null]],[[null,null],[null,null]]]]}';
//updating last tournament bracket.
$sql1 = "UPDATE lan_brackets SET json='$final' ORDER BY tid DESC LIMIT 1;";
$roundOne=$conn->query($sql1);
?>

join query not working properly

I want to select two table values so I am using join query see below, from this code I stored one session variable like $_SESSION['emp_id'], I want select query like who are in te.emp_id='".$_SESSION['emp_id']."', From this code $count will return 0 but in my database I have one row.
$q = mysql_query("SELECT *
FROM task_employee te
JOIN task t
ON te.emp_id = t.t_assign_to
WHERE t.t_status = '0'
AND t.t_delete_on != '1'
AND te.emp_id = '" . $_SESSION['emp_id'] . "'");
$data = array();
while($r = mysql_fetch_assoc($q))
{
$data[] = $r;
}
$count = sizeof($data);
if($count > 0)
{
$return = array('status'=>'success', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
else
{
$return=array('status'=>'not-found', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
I am writing like this means I can get but using join query that time I can't get values
<?php
$sql = mysql_query("SELECT *
FROM task
WHERE t_delete_on !='1'
AND t_assign_to = '$emp_id'");
for ($i = 1; $row = mysql_fetch_assoc($sql); $i++)
{
$assign_to = $row['t_assign_to'];
$mysql = mysql_query("SELECT *
FROM task_employee
WHERE emp_id = '$assign_to'");
while ($r = mysql_fetch_assoc($mysql))
{
$emp_name = $r['emp_firstname']; // here i got value
}
}
?>

Fetching data from database, not getting correct data

I have a database which looks like so -
I am trying to fetch the top 10 entries based on time (entries with top 10 values in time column). I have the following code.
<?php
include_once("connect.php");
$sql = "SELECT * FROM scores order by time desc limit 10";
$query = mysql_query($sql) or die("systemResult=Error");
$counter = mysql_num_rows($query);
if($counter>0)
{
print("systemResult=Success");
$array = mysql_fetch_array($query);
foreach($array as $data)
{
$athleteName = $data["athleteName"];
$email = $data["email"];
$time = $data["time"];
$timeStamp = $data["timeStamp"];
$country = $data["country"];
print "&athleteName=" . $athleteName;
print "&email=" . $email;
print "&time=".$time;
print "&timeStamp=".$timeStamp;
print "&country=".$country;
}
}
else
{
print("systemResult=Error");
}
?>
The output I am getting is
systemResult=Success&athleteName=7&email=7&time=7&timeStamp=7&country=7&athleteName=7&email=7&time=7&timeStamp=7&country=7&athleteName=4&email=4&time=4&timeStamp=4&country=4&athleteName=4&email=4&time=4&timeStamp=4&country=4&athleteName=G&email=G&time=G&timeStamp=G&country=G&athleteName=G&email=G&time=G&timeStamp=G&country=G&athleteName=n&email=n&time=n&timeStamp=n&country=n&athleteName=n&email=n&time=n&timeStamp=n&country=n&athleteName=2&email=2&time=2&timeStamp=2&country=2&athleteName=2&email=2&time=2&timeStamp=2&country=2&athleteName=I&email=I&time=I&timeStamp=I&country=I&athleteName=I&email=I&time=I&timeStamp=I&country=I
As can be seen, the output I am getting is not what is on the table in database. I am getting wierd values. What am I doing wrong?
You don't need to use for each in your case, and if so, just print $data, try to remove foreach loop, and if you want to get all records, then, use while:
while($data = mysql_fetch_array($query))
{
$athleteName = $data["athleteName"];
$email = $data["email"];
$time = $data["time"];
$timeStamp = $data["timeStamp"];
$country = $data["country"];
print "&athleteName=" . $athleteName;
print "&email=" . $email;
print "&time=".$time;
print "&timeStamp=".$timeStamp;
print "&country=".$country;
}
try
while($data = mysql_fetch_array($query)) {
$athleteName = $data["athleteName"];
//...

pq_query error on update

I'm new to postresql and i am ashamed to recognize that i am not sure how tot execute correctly an update .
Every time I am trying to pg_query($update); it gives me this : Query failed: ERROR: cannot execute UPDATE in a read-only transaction .
Before this update I have executed a select query .
The select statement retrieves 50000 rows from the database. To be even more specific I am trying to execute a when /case update on 1000 rows. The query is well-formed I have tested it .
$sqlstr = "update abcd set country = CASE" ;
$temp = "";
while($myrow = pg_fetch_assoc($result)) {
if ($cnt < 1000) {
$country = exec('geoiplookup '.$myrow['ip']);
$temp .= " WHEN id = ".$myrow['id']." then '".$country."'";
$cnt++;
}
else {
$sqlstr = $sqlstr.$temp." END ; ";
pg_query($sqlstr);
$temp = "";
}
}
$sqlstr = "update abcd set country = CASE" ;
$temp = "";
while($myrow = pg_fetch_assoc($result))
{
if ($cnt < 1000)
{
$country = exec('geoiplookup '.$myrow['ip']);
$temp .= " WHEN id = ".$myrow['id']." then '".$country."'";
$cnt++;
}
else
{
$sqlstr = $sqlstr.$temp." END ; ";
pg_query($sqlstr);
$temp = "";
}
}

Fetch all rows for each row in a database

I have a database with list of members. I execute a certain query it selects all members satisfying a condition. Then for each member in resultset, I want to send the details of all members generated in output and continue the loop until end of resultset. My current SQL query is:
if( $result || mysql_num_rows($result) != 0)
{
$string = "result";
while($r = mysql_fetch_array($result,MYSQL_ASSOC))
{
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$string .= "," . $row['latitude'] . "," . $row['longitude'];
$i = $i + 1;
}
**$registration_id = $r['user_id'];**
}
}
This does not give me an intended result? Any loopholes or bugs in this?
The first while fetches the entire row as an array. The second while made no sense.
if( $result || mysql_num_rows($result) != 0)
{
$string = "result";
while($r = mysql_fetch_array($result,MYSQL_ASSOC))
{
$string .= "," . $r['latitude'] . "," . $r['longitude'];
$i = $i + 1;
//Send notification to that member
}
}
Try without first WHILE
if( $result || mysql_num_rows($result) != 0)
{
$string = "result";
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$string .= "," . $row['latitude'] . "," . $row['longitude'];
$i = $i + 1;
}
//Send notification to that member
}
Try the foreach PHP loop
Like This;
Query the database and build an array of the members given the specific conditions and build the members array like this
$members = array(); // Intialize Empty Array
$sql = "SELECT member_name FROM .... WHERE ... "; // Ensure you're selecting one field here
while($result = $mysql_fetch_assoc(mysql_query($sql)))
{
$members[]=$result['member_name'];//This is the members array we're adding members to
}
//Get Members Array Count
$member_count = count($members);
//Check whether members array is more than 0
if($member_count != 0)
{
//Do for each loop to select profiles for each member in our array
foreach($members as $key)
{
$sql = " SELECT email,number,imei,device,latitude,longitude,userID FROM ... WHERE member_name LIKE '$key' ";
while($result = $mysql_fetch_assoc(mysql_query($sql)))
{
//print results here
.
.
.
}
}
}

Categories