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
.
.
.
}
}
}
Related
hi guys im trying to insert a mysql data to a variable that will set an if condition depending on the result. is this possible, am i doing it right? what is the right way to do it ? what i want to achieve is to validate if there's a equal value given by the user inside my mysql rows.
$db = mysql_connect('localhost','test','');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
$dbname = 'test';
$btest = mysql_select_db($dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
$sql_statement = "SELECT * ";
$sql_statement .= "FROM registered_email ";
$result = mysql_query($sql_statement);
$outputDisplay = "";
$myrowcount = 0;
if (!$result) {
$outputDisplay .= "<br /><font color=red>MySQL No: ".mysql_errno();
$outputDisplay .= "<br />MySQL Error: ".mysql_error();
$outputDisplay .= "<br />SQL Statement: ".$sql_statement;
$outputDisplay .= "<br />MySQL Affected Rows: ".mysql_affected_rows()."</font><br />";
}
else{
$numresults = mysql_num_rows($result);
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
}
}
and here what im trying to achieve, btw is $clientEmail has a default values so dont worry about that.
if($clientEmail === $outputDisplay){
...... some codes..........
}
else{
....... some codes.......
}
you can use mysql row to compare with your user input. you can add condition, while you'r getting row value for the email inside the loop.
$email_exist = 0;//define the default value.
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist = 1;
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
why don't you use a while loop?
make sure to update to mysqli_* because mysql_* is deprecated and is going to get removed on php 7.0
$email_exist = 0;//define the default value.
while ( $row = mysql_fetch_assoc($result) ) // you are using associative array and not the indexed once tho you should go for mysql_fetch_assoc
{
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist += 1; //maybe it exist more than once?
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
or you can do something more simple like this
$query = "select email from tablename where email='$clientemail'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count > 0) {
// email exists
} else {
// doesn't exist
}
I want to insert an array in the database. The array can be changed all the time. I want different rows in the database.
My code:
$var = file_get_contents("test2.txt");
$test = preg_replace('/\\\\/', '', $var);
$poep = explode(" ", $test);
Yeah, there is no database connection, because I want to know how to 'split' the array to insert it in the database.
I have tried this:
foreach($poep as $row) {
$row = $mysqli->real_escape_string($row);
if($mysqli->query("insert into data('array') VALUES ($row)") == false){
echo 'Doesnt works!';
}
It returns 'Doesnt works', so I think there is a problem with query?
#NadirDev Hi. Assuming that you are using Core PHP programming. After exploding the string by the space, run foreach loop and then insert individual rows. Look at this rough code to get idea:
foreach($poep as $row) {
// $row now contains one word. Add that in database.
$row = mysql_real_escape_string($row);
$query = mysql_query("insert into tableName('fieldName') VALUES ($row)");
}
here's some code I wrote. It processes a CSV file and stores separate rows into a db table (difference is just that you have a TXT file). It does the mysql insertion in batches of 250 rows. Hope it can help you!
// read all input rows into an array
echo "Processing input..<br /><br />";
$row = 0;
$input = array();
if (($handle = fopen($file['tmp_name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$input[$row][] = addslashes($data[$c]);
}
$row++;
}
fclose($handle);
}
$count = 0;
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
foreach ($input as $inp) {
$q .= "('" . addslashes($inp[0]) . "', '" . addslashes($inp[1]) . "', '" . addslashes($inp[2]) . "', '" . date('Y-m-d H:i:s') . "'), ";
$count++;
if ($count >= 250) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
$count = 0;
}
}
if ($count > 0) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
}
echo "Successfully added " . count($input) . " rows to the input list.";
I new to php and mysql.
I wrote the function below:
function catOption() {
$maincatfunc_query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$funcCat = array();
while ($mainCatFunc = mysql_fetch_array($maincatfunc_query)) {
for ($i = 0; $i < count($maincatfunc_query); $i++) {
$funcCat[$i] = '<option value="'.$maincatfunc_sorgu['mainCatID'].'">' . $maincatfunc_sorgu['name'] . '</option>';
}
}
for ($i = 0; $i < count($maincatfunc_query); $i++) {
return $funcCat[$i];
}
}
I want to fetch "all" value from mysql database and fill it in a dropdown. So i wrote a function like this. But it does not work.
And i don't think count() function doesn't really work in this conditions. How can i get the max count of mysql array ?.
or besides can i do this without using a function ?. I've googled it for a long time but i can't find any usefull info.
Thanks !
You should use like below: [returns array]
function catOption()
{
$query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$arrCat = array();
while ($row = mysql_fetch_array($query)) {
$arrCat[] = '<option value="'. $row['mainCatID'].'">'. $row['name'].'</option>';
}
return $arrCat;
}
Or this one [returns string]
function catOption()
{
$query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$arrCat = "";
while ($row = mysql_fetch_array($query)) {
$arrCat .= '<option value="'. $row['mainCatID'].'">'. $row['name'].'</option>';
}
return $arrCat;
}
You should try this,
function catOption() {
$maincatfunc_query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
while ($mainCatFunc = mysql_fetch_array($maincatfunc_query)) {
$funcCat .= '<option value="'.$mainCatFunc['mainCatID'].'">' . $mainCatFunc['name'] . '</option>';
}
return $funcCat;
}
Use like this :
$dropDownData = catOption();
put it into HTML
<select><?php echo $dropDownData; ?></select>
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 = "";
}
}
I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:
<?php
header("Content-type: application/json");
echo '{"points":[';
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";
$res = mysql_query($q) or die(mysql_error());
while ($point = mysql_fetch_assoc($res)) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
mysql_free_result($res);
echo ']}';
?>
Could you not use json_encode() instead, rather than hand-crafting the JSON?
$result = array();
//snip
while ($point = mysql_fetch_assoc($res)) {
$result[] = $point['lat'];
$result[] = $point['lon'];
$result[] = $point['temperature'];
}
//snip
header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Use a count query to get the number of rows to begin with.
$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);
Then introduce a conditional and a count decrease each time through...
while ($point = mysql_fetch_assoc($res)) {
$count = $count - 1;
if ($count == 1) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
} else {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
Json encode would probably be your best bet, but you could also use trim();
Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.
About the comma problem, I always target the first item instead of the last:
$first = true;
while ($point = mysql_fetch_assoc($res)) {
if ($first)
{
$first = false;
}
else
{
echo ",";
}
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
You can use mysql_num_rows() to find out how many rows are in the result set passed back from your last query.
...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);
Then combine that with Scotts answer and you should be set.