I have this php function which checks a table in a database and checks to see if a user has a specific number in a field . This user could have a few rows where that filed has that number .
The problem with this is that it will run the if statement multiple times, triggering the resulting function to run multiple times. How can I stop this and just have the function say "okay found a match for al1 and running function , moving onto al2"
function countNewBadges() {
require "connect.php";
$count = mysqli_query($connection,"SELECT users.studentid, al1, al2, al3 FROM userbadges ub INNER JOIN users ON users.id = ub.user_id WHERE studentid = '".$_SESSION["studentid"]."'") or die(mysqli_error($connection));
while ($data = mysqli_fetch_array($count)) {
if ($data['al1'] == 1)
{
unlockedBadges();
}
else if ($data['al2'] == 1)
{
echo "No New Badges";
}
else if ($data['al3'] == 1)
{
echo "No New Badges";
}
}
}
How can I have the function say "okay found a match for al1 and running function, moving onto al2"
Just use a flag variable:
$flag = false;
while ($data = mysqli_fetch_array($count)) {
if ($data['al1'] == 1 && $flag === false)
{
unlockedBadges();
$flag = true;
}
else if ($data['al2'] == 1)
{
echo "No New Badges";
}
else if ($data['al3'] == 1)
{
echo "No New Badges";
}
}
While user4035's answer will stop multiple data entries to truly only run a function once you need to search and then act after (using as was said) a flag.
function countNewBadges() {
require "connect.php";
$count = mysqli_query($connection,"SELECT users.studentid, al1, al2, al3 FROM userbadges ub INNER JOIN users ON users.id = ub.user_id WHERE studentid = '".$_SESSION["studentid"]."'") or die(mysqli_error($connection));
$foundit=false;
while ($data = mysqli_fetch_array($count)) {
if ($data['al1'] == 1)
{
$foundit=true;
}
else if ($data['al2'] == 1)
{
echo "No New Badges";
}
else if ($data['al3'] == 1)
{
echo "No New Badges";
}
}
if($foundit){
unlockedBadges();
}
}
Related
I'm having an issue trying to update my database. I'm able to insert if it doesn't exist, but it doesn't update the record if exists. I think is not finding the current values of the table. Any ideas?
<?php
function add_log($input_output, $l_sales, $l_enroll, $l_offers)
{
global $database;
$date = date('m-d-Y');
$l_sales = safety_filter($l_sales);
$l_enroll = safety_filter($l_enroll);
$l_offers = safety_filter($l_offers);
$cusersup = get_the_current_user('u_manager');
$cuseropm = get_the_current_user('u_opsmanager');
$cuserid = get_the_current_user('id');
$cuser = get_the_current_user('user_name');
if($input_output == 'input')
{
$query_call = mysql_query("SELECT 1 FROM $database->log WHERE l_date='$date' AND l_user_name='$cuser'");
if(mysql_num_rows($query_call) > 0)
{
while($list_calls = mysql_fetch_assoc($query_call))
{
$old_calls = $list_calls['l_calls'];
$old_sales = $list_calls['l_sales'];
$old_enroll = $list_calls['l_enroll'];
$old_offers = $list_calls['l_offers'];
}
$update = mysql_query("UPDATE $database->log SET
l_call=[$old_calls] + [1],
l_sales=[$old_sales] + [$l_sales],
l_enroll=[$old_enroll] + [$l_enroll],
l_offers=[$old_offers] + [$l_offers]
WHERE l_date='$date' AND l
_user_name='$cuser'");
if(mysql_affected_rows() > 0){return true; }
else { if($update == true){ return true; } else { return false; } }
}
else
{
mysql_query("INSERT INTO $database->log (l_date, l_user_name, l_calls, l_sales, l_enroll, l_offers) VALUES ('$date', '$cuser', '1', '$l_sales', '$l_enroll', '$l_offers')");
if(mysql_affected_rows() > 0){return true; }
else{ return false; }
}
}
}
?>
I think the problem is that you are selecting 1 ("SELECT 1 FROM..."), so you are never getting any of the values from the table (just the number "1"). This tells you something is there, but doesn't actually return any values.
Try selecting all fields ("SELECT * FROM..."), or at least list the fields you need to do the update.
I want to match the ID of two tables then if the ID matched redirect it to specific page.
SELECT user_skill.user_id AS id_one, job_seeker.user_id AS id_two
FROM user_skill
INNER JOIN job_seeker ON (user_skill.user_id = job_seeker.user_id)
using this condition below
if(mysqli_num_rows($result) > 0) {
while($fetch = mysqli_fetch_assoc($result)) {
if($fetch['id_one'] === $fetch['id_two']) {
header('location: userhome.php');
}
else {
header('location: userskill.php');
}
}
}
Any suggestions would be helpful. Thanks!!
SELECT user_skill.user_id AS id_one, job_seeker.user_id AS id_two
FROM user_skill
INNER JOIN job_seeker ON (user_skill.user_id = job_seeker.user_id)
using this condition below
if(mysqli_num_rows($result) > 0) {
while($fetch = mysqli_fetch_assoc($result)) {
$variable=array($fetch['id_one']=>$fetch['id_two']);
foreach($variable as $x=$value)
{
if($x === $value) {
header('location: userhome.php');
}
else {
header('location: userskill.php');
}
}
}
}
I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
I have an admin area where they can delete multiple users at a time. This is part of the code that handles the deletion. Basically it goes through the user ids and deletes each one that was marked checked.
if ($_POST['doDelete'] == 'Delete') {
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = escape($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$msg->add('e', QUERY_ERROR);
redirect('users.php');
exit();
}
}
}
/* we need a way to iterate over users deleted */
$msg = new Messages();
$msg->add('s', QUERY_DELETE_SUCCESS);
redirect('users.php');
exit();
}
function get_user_name_from_id($user_id)
{
if ($_SESSION['user_level'] == ADMIN_LEVEL) {
$viewUserMod = 1;
} else {
$config = Nemesis::select("usr_view_cm", "config");
$row_config = $config->fetch_assoc();
$viewUserMod = $row_config['usr_view_cm'];
}
if (is_numeric($user_id) && $viewUserMod == 1) {
$sql = Nemesis::select("full_name", "users", "id = {$user_id}");
if ($sql->num_rows > 0) {
$user_name = $sql->fetch_assoc();
return $user_name['full_name'];
} else {
// user name cannot be matched with db, either error, or most likely user was deleted
return 'User ' . $user_id;
}
} else {
return $user_id;
}
}
Where it says QUERY_DELETE_SUCCESS I would like to output something like "Deleted Bob, Jack, Tim" .etc I have a function that uses the users id and gets their names. The issue is that once the iteration is complete. Obviously those users no longer exist in the database and I cannot get their names. Is there a way of running this function during the loop, and building a string or array. That can be outputted in place of the message?
You should just be able to do this:
if ($_POST['doDelete'] == 'Delete') {
$deleted = array();
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = escape($uid);
$username = get_user_name_from_id($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$msg->add('e', QUERY_ERROR);
redirect('users.php');
exit();
}
$deleted[] = $username // push name to array after deletion is successful
}
}
/* The $deleted array now holds the names of the deleted users.
* Do with it what you want.
*/
$names = implode(",", $deleted)
$msg = new Messages();
$msg->add('s', QUERY_DELETE_SUCCESS . " Deleted: $names");
redirect('users.php');
exit();
}
There are several improvements that can be made here, including efficiency (combining many small single queries into a few larger ones) and error handling (don't redirect on the first error - instead redirect after all processing is complete to a page with a list of successes and errors), but this is the basic idea.
Here is a quick change that will do all of the operations, even if one of them errors:
if ($_POST['doDelete'] == 'Delete') {
$deleted = array();
$errored = array();
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = escape($uid);
$username = get_user_name_from_id($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$errored[] = $username;
} else {
$deleted[] = $username // push name to array after deletion is successful
}
}
}
/* The $deleted array now holds the names of the deleted users.
* The $errored array now holds the names of users who were not deleted due to errors.
* Do with them what you want.
*/
$msg = new Messages();
$names_deleted = implode(",", $deleted)
$msg->add('s', QUERY_DELETE_SUCCESS . " Deleted: $names_deleted");
if (count($errored) > 0) {
$names_errored = implode(",", $errored)
$msg->add('e', QUERY_ERROR . " Did not delete: $names_errored");
}
redirect('users.php');
exit();
}
You could add the names to an array as you are looping over the uids with something like this:
$names = array();
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$names[] = get_user_name_from_id($uid);
$id = escape($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$msg->add('e', QUERY_ERROR);
redirect('users.php');
exit();
}
}
}
Then when you want to output the confirmation message, you could turn that array into a comma separated string with something like this:
$names = implode(', ',$names);
$message = "Deleted $names";
I am dying here :-) Please help out!
The following query gets different messages for different users from the same table based on current time.
$message = mysql_query("SELECT * FROM `table`
WHERE `Scheduled` <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 MINUTE)
AND `Status` != 'published'");
/** Kill db connection and exit script if no results are found **/
if (mysql_num_rows($message)== 0) {
mysql_close($db) && exit();
}
else {
while ($row = mysql_fetch_array($message))
{
$msg = $row["Messages"];
$accnt = $row["Account"];
{
if ($accnt == 'Account1')
echo $msg.$accnt;
elseif ($accnt == 'Account2')
echo $msg.$accnt;
else
echo "Nothing Here!";
}
}
}
This only echos the first account, please help I have a headache. I have run this on the db directly and it works fine. I believe I am messing up in php
I think you are getting non associative array. If you wanna assoc. array, you have to change it :
while ($row = mysql_fetch_array($message))
to
while ($row = mysql_fetch_assoc($message))
//you have made a drastic mistake in your code check now it will work
if (mysql_num_rows($message)== 0) {
mysql_close($db) && exit();
}
else {
while ($row = mysql_fetch_array($message))
{
$msg = $row["Messages"];
$accnt = $row["Account"];
if ($accnt == 'Account1')
echo $msg.$accnt;
elseif ($accnt == 'Account2')
echo $msg.$accnt;
else
echo "Nothing Here!";
}
}