Hi i am querying my db so that i can compare every two rows. ex 1 and 2, then 2 and 3, then 3 and 4. and so on and so forth. but it only compares the first two rows. any ideas? here is my code:
$result = mysql_query("SELECT *FROM attendance ORDER BY pid ASC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// $response["nominees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$prev_sid = $row["sid"];
$prev_pid = $row["pid"];
$row2 = mysql_fetch_array($result);
if($row2["pid"] == $prev_pid){
if(($row2["sid"] - $prev_sid) == 1){
$attended_elec = mysql_query("SELECT pid FROM election_attendance where election_id = '$election_id'");
if(mysql_num_rows($attended_elec) > 0){
$not_officer = mysql_query("SELECT usertype FROM users WHERE pid = '$prev_pid'");
if(mysql_result($not_officer, 0) == "member"){
// echo "PID" . $prev_pid;
// $nominee["pid"] = $row2["pid"];
$user_details = mysql_query("SELECT *FROM users WHERE pid = '$prev_pid'");
if(mysql_num_rows($user_details) > 0){
$response["nominees"] = array();
while ($row3 = mysql_fetch_array($user_details)) {
$nominee = array();
$nominee["pid"] = $row3["pid"];
$nominee["firstname"] = $row3["firstname"];
$nominee["lastname"] = $row3["lastname"];
$nominee["gender"] = $row3["gender"];
$nominee["contact"] = $row3["contact"];
$nominee["email"] = $row3["email"];
$nominee["address"] = $row3["address"];
$nominee["institution"] = $row3["institution"];
$nominee["points"] = $row3["points"];
$nominee["usertype"] = $row3["usertype"];
// push single product into final response array
array_push($response["nominees"], $nominee);
}
}
}
}
}
}
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "There is no candidate yet from the records.";
// echo no users JSON
echo json_encode($response);
}
thanks in advance, have a nice day
Theres a problem right at the while(), you're fetching the 1st row, and is correct.
Then, inside it you fetch the 2nd, which is what you intend, but when the iteration is repeating, the while will fetch the 3rd, and the inner the 4th, so you lost there the comparisson between 2nd and 3rd.
// fetch data from DB
$results = "...";
if (mysql_num_rows($result) < 1)
{
// no products found tell your users
return;
}
// lets make some variables to walk through the list
$previous = mysql_fetch_array($results);
$actual = null;
// and now lets walk through the list
while($actual = mysql_fetch_array($results))
{
// execute your logic here
// than at the end move the actual row to become the previous
$previous = $actual;
}
NOTICE you shouldn't use mysql_ * methods they're are deprecated. you can use the brother mysqli_ * or PDO
I would do something like this? But there is almost certainly a less resource intensive way to do it.
$x = 0;
$y = 1;
$total = mysql_num_rows(mysql_query("SELECT * FROM `the_place`");
while ($x < $total AND $y < total){
$query1 = "SELECT * FROM `the_place` LIMIT $x,1";
$query2 = "SELECT * FROM `the_place` LIMIT $y,1";
$row1 = mysql_fetch_array(mysql_query($query1);
$row2 = mysql_fetch_array(mysql_query($query2);
// Do comparison here
if ($row1 == $row2){
// etc
}
$x = $x++;
$y = $y++;
}
Related
Please I've been trying to create a function that would query a DB, select from the table, and if the row count is not equal to 6, then a row from the table and repeat (or maybe duplicate) until the row count is equal to 6. I've search for this here in StackOverflow, but didn't get anything close. Please if you have a similar link to this, please post it here, and I'll give it a go.
Here's my code:
//List All active adverts
function showActiveAdverts()
{
$status = 1;
//Build final queries.
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
# My question here, check if the $count >= 1 && $count != 6, then do getDefaultBannner() and repeat it until it runs for 6 times.
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Here's the code for getDefaultBannner()
function getDefaultBannner()
{
$status = 6;
$query = mysql_query("SELECT id FROM table WHERE status = '".mysql_real_escape_string($status)."' ")
or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Thanks in advance!
You can rewrite your code as this
//List All active adverts
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
if($count >= 1 && $count != 6)
$list = getDefaultBannner();
else
$list = showActiveAdverts($query);
function showActiveAdverts($query)
{
$status = 1;
//Build final queries.
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.
I am in the process of learning mysqli and I am trying to query a databases and return multiple rows. I understand that a loop has to be used to return multiple rows but I have no idea how I would implement this into my code. Some help in doing this would be greatly appreciated.
$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$count = mysqli_num_rows($query2);
if ($count == 0) {
$journeys = 'You have no future journeys.';
} else {
while ( $row = mysqli_fetch_assoc($query2) ) {
$from = $row ['origin'];
$to = $row ['destination'];
$date = $row ['date'];
$hour = $row ['hour'];
$minute = $row ['minute'];
$journeyid = $row ['journeyid'];
try this code
<?php
$con= mysqli_connect('localhost', 'root', '', 'your data base name');
$query2 = mysqli_query($con,"SELECT * FROM journeys where id=$id");
$count = mysqli_num_rows($query2);
if ($count == 0) {
$journeys = 'You have no future journeys.';
echo $journeys;
} else {
while ( $row = mysqli_fetch_assoc($query2) ) {
$from = $row ['origin'];
$to = $row ['destination'];
$date = $row ['date'];
$hour = $row ['our'];
$minute = $row ['minute'];
$journeyid =$row ['journeyid'];
echo $from.'<br>';
}
}
have a look at this line echo $from; this will display what ever you have in the origin column in your database, if you want to display destination, use this as well echo $to;
means what ever you want to display do it like this echo $variableName; it will display the result;
before you display the result it will only store it, but will not display it,
have a look i change your this line of code as well
its your code
if ($count == 0) {
$journeys = 'You have no future journeys.';
echo $journeys;// i added this line
i added one line, because what you are saying here that if $count is equal to zero, than $journeys='you have no future journeys'; but you are not using echo you have to use echo to display the result.
if you still have some confusion ask again, and try to google as well
$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$row = mysql_fetch_array($query2);
$count = count($row);
if(intval($count)>0)
{
for($i = 0; $i<$count; $i++)
{
$from[$i] = $row[$i]['origin'];
-------------------------------
----------------------
}
}
I have been racking my brains trying to get something that seems simple to work. I have a TABLE "weight". Weight has 3 columns "shipping_to", "shipping_from", and "shipping_cost".
Shipping_to and Shipping_from are the weight values and shipping cost holds the shipping cost if the value is greater than or equal to X AND less than or equal to X.
I have written this a million different ways and for the life of me it won't work.
UPDATED:
The Script works "kind of" but it never returns a success response of 1 and it never fimds the value of X even though I have manually put these values into my MySQL db.
PHP SCRIPT:
if($The_Function=="SHIPPING_COST"){
$response = array();
require_once __DIR__ . '/db_connect.php';
$con = new DB_CONNECT();
$ship_weight = 1;
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
if(!empty($result)){
if (mysql_num_rows($result) > 0) {
$response["userID"] = array();
while ($row = mysql_fetch_array($result)) {
$custID = array();
$custID["shipping_cost"] = $row["shipping_cost"];
array_push($response["userID"], $custID);
}
$response["success"] = 1;
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}
The error was in the Query itself. All I had to do was give the last Column something to compare to so I just added $ship_weight again. Here is the code.
$result = mysql_query("SELECT * FROM weight WHERE '$ship_weight' >= from_weight AND '$ship_weight' <= to_weight");
I think the problem is that $result will never be empty()
If the query works if will be a resource handle and if it fails it will be false.
So try this:
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
if($result !== FALSE){
if (mysql_num_rows($result) > 0) {
$response["userID"] = array();
while ($row = mysql_fetch_array($result)) {
$custID = array();
$custID["shipping_cost"] = $row["shipping_cost"];
array_push($response["userID"], $custID);
}
$response["success"] = 1;
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
Is this a copy and paste of your code? If so, look at this line:
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
PHP is considering your $ship_weight variable as part of the string. Change it to:
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '".$ship_weight."' AND to_weight <= '".$ship_weight."'");
Also, mysql_* is deprecated. Take a look at the mysqli_* extension.
I'm using PHP/MySql and I'm trying to team users into pairs based on a skill that they have. I have an existing table for users, and an existing table for the teams.
For example, I executed a query which returned 6 members which needs to be paired up into a team.
SELECT * FROM users WHERE skill = 'Office'
users
id/name/skill
1/Bob/Office
2/Ted/Office
3/Tim/Office
4/Bill/Office
5/Shawn/Office
6/Gab/Office
These results must be then paired up, and the expected output should be:
teams
name/member
Office1/Bob
Office1/Ted
Office2/Tim
Office2/Bill
Office3/Shawn
Office3/Gab
Once 2 members are placed in a team, the team name should increment by one.
Any help will be greatly appreciated Thanks.
Edit: I tried this:
$results = mysql_query("SELECT * FROM users WHERE skill = 'Office'");
$numrows = mysql_num_rows($results); $name ="";
if($numrows!=0) {
while($row = mysql_fetch_assoc($results)) {
$name = $row['userName'];
}
}
//For incrementing the team name
$namectr=0;
for($ctr=0;$ctr<$results_num;$ctr++) {
if($ctr%2==0) {
$query = mysql_query("INSERT INTO teams VALUES ('Office$namectr','$name')");
$ctr++; if($ctr%2==1) {
$query = mysql_query("INSERT INTO teams VALUES (Office$namectr','$name')");
$namectr++;
}
}
}
why not try:
$result = mysql_query("SELECT * FROM users WHERE users.skill = 'office'");
$count = 0;
$sqlcount = 0;
$offcount = 1;
while ($source = mysql_fetch_array($result)) {
if ($count < 1) {
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else if ($count >= 1) {
$offcount++;
$count = 0;
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else {
echo "ERROR" . mysql_error();
}
}//end while
$sqlcount = 0;
while ($result[$sqlcount] != "") {
if ($source = $result) {
} else {
echo "ERROR! " . mysql_error();
}
}//end while
Couldn't you do your database query, then do something like the below:
$count=0;
$team=1;
$teams = array();
foreach($result as $output){
if($count % 2 == 0){
// if even number, reset count and increment position
$count=0;
$team++;
}
$teams[] = $output['skill']." ".$team." - ".$output['member'];
$count++;
}
Something like the above, but it is untested, but should work in theory.