Show alert message if MySQL php query match one condition [duplicate] - php

This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance

Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.

you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}

Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks

Related

Displaying results from SQL query in PHP in a table

I am having some trouble with displaying some SQL query results.
Goal: I want to display the Helper 'name' in the table that is being generated if there is a helper signed up in the 'signup' table for that event 'eid' (event id).. If (1)there is no helper then display 'waiting for help', (2) there is a helper then display 'name -- awaiting approval..' and (3) else just display the name of helper..
Tried running the SQL query in phpMyAdmin with hard coded values and I get the results that I want so I know it is not my query. Have a suspicion that it is just the print out of the info into the table that is wrong somewhere. The table will display the data up until the ZIP from the address and then the next column which is the 'Helper' column does not display anything at all. So it makes me think I have a simple typo somewhere based on my if() statement logic BUT also find it interesting also that when I do the line:
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
I cant get the table to print out at all. Not sure if this is related to my exact issue but it seems it could be. After I put this function in stuff stopped working so it seems like it could be culprit. The return of the function should either return an ID (int), a name "string", or just a generic value X (string)..
Any and all help is appreciated!
function getHelperIdOrName($x, $eid){
//Get the helper name first
$helperName = "";
$helperId = 0;
$sql = "SELECT id, first FROM users WHERE id IN (SELECT helper FROM signup WHERE gner = '".$userId."' AND eid = '".$eid."')";
$result = mysqli_query($db,$sql);
$row = $result->fetch_assoc();
if ($x == 2){
$helperName = $row["first"];
return $helperName;
}
else if ($x == 1){
$helperId = $row["id"];
return $helperId;
}
else {
return "X";
}
}
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
//look for calendar and/or business approved events (approved=1) to display on page
$sql = "SELECT s.gner, s.helper, s.eid, s.approved, e.name, e.date, e.summary, e.street, e.city, e.state, e.zip
FROM signup s
INNER JOIN events e ON e.id = s.eid
INNER JOIN users u ON u.id = s.gner
WHERE s.gner = '".$userId."'";
$result = mysqli_query($db,$sql);
echo "<h3 class=\"text-center\">Events I'm Going To</h3>";
echo "<table class=\"table table-hover\"><tr><th>Event Name</th><th>Date</th><th>Summary</th><th>Location</th><th>Helper</th><th>Remove</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["date"]."</td><td>".$row["summary"]."</td><td>".$row["street"].", "
.$row["city"].", ".$row["state"]." ".$row["zip"]."</td>";
$tmp_eid = $row["eid"];
if (getHelperIdOrName(2, $temp_eid) == "X"){
echo "<td>Waiting for help..</td>";
}
else if ($row["approved"] == 0){
echo "<td>".getHelperIdOrName(2, $temp_eid)." -- Awaiting Approval (see below)</td>";
}
else {
echo "<td>".getHelperIdOrName(2, $temp_eid)."</td>";
}
echo "<td><form method=\"post\" action=\"remove.php\">
<button type=\"submit\" name=\"remove\" value=\"".$row["eid"]."\">Not Going</button></form></td></table>";
}
}
else echo "</table><br><p class=\"text-center\">You are not signed up for any events. Click here to sign up for events near you!</p>";
Thanks for that Jeff. The issue was that inside of the function it indeed did not know what $userId was even though I had the include statement at the top of my php file. I had to add this line into my function at the top..
global $db; //is part of my db my connection info in my config.php file
and then I also passed the $userId to the function as a parameter
these lines are what I used to help me see the errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
i also had some ending < /table > tags inside some if logic so that fixed the funky displays I was getting (2nd row of table being outside of the table)

Give another random int if number exists in database (PHP)

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!

PHP code not running successfully

My question is very simple. The code I have written here produces absolutely no output on the webpage. I've been at it all day and I'm sure that it's something very simple that I am being an idiot for missing. So I am appealing to your good-natured fresh eyes! If anyone can spot a reason why this isn't working, I'd be very grateful.
The premise:
This is a decision tree online survey that has the following conditions: if a user has already started the survey, it will find them in the database, find their last answered question and display the next one. But if they haven't started, it will display the first question.
All survey questions are held in the database as well as the decision tree logic (for instance, if the user chooses option 2 for question 1, they will be directed to question 3, not 2).
Please assume that for the moment, I am updating relevant info directly from the database and not automating it on the website.
Thanks :)
PHP:
<?php
//Find the latest question reached by the user for display on the page
$sql = mysql_query("SELECT QuestionNumberReached FROM User WHERE EmailAddress = '***'");
$sqlCount = mysql_num_rows($sql);
if ($sqlCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$QuestionNumberReached = $row["QuestionNumberReached"];
}
}
?>
<?php
//Find the last question answered by the user from the database
$StartedQuery = mysql_query("SELECT LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//Count the number of rows that the query produces
$StartedQueryCount = mysql_num_rows($StartedQuery);
//If data is found, whether it be a number or null, define the value
if ($StartedQueryCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$LastQuestionAnswered = $row["LastQuestionAnswered"];
//If the field has a value and is not null, find the next question from the database
if (!empty($LastQuestionAnswered)) {
//Find the User's ID and the ID of the last question answered
$sqlA = mysql_query("SELECT PKID, LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//If the operation produces an error, output an error message
if (!$sqlA) {
die('Invalid query for SQLA: ' . mysql_error());
}
//Count the number of rows output
$sqlACount = mysql_num_rows($sqlA);
//If rows exist, define the values
if ($sqlACount > 0) {
while ($row = mysql_fetch_array($sqlA)) {
$sqlAPKID = $row["PKID"];
$sqlALastQuestionAnswered = $row["LastQuestionAnswered"];
}
}
//Find the answer given by the user to the last answered question
$sqlB = mysql_query("SELECT Answer FROM Responses WHERE User = $sqlAPKID");
//If the operation produces an error, output an error message
if (!$sqlB) {
die('Invalid query for SQLB: ' . mysql_error());
}
//Count the number of rows output
$sqlBCount = mysql_num_rows($sqlB);
//If rows exist, define the values
if ($sqlBCount > 0) {
while ($row = mysql_fetch_array($sqlB)) {
$sqlBAnswer = $row["Answer"];
}
}
//Find the number of the next question to be answered based on the user's previous answer and the question they answered
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");
//If the operation produces an error, output an error message
if (!$sqlC) {
die('Invalid query for SQLC: ' . mysql_error());
}
//Count the number of rows output
$sqlCCount = mysql_num_rows($sqlC);
//If rows exist, define the values
if ($sqlCCount > 0) {
while ($row = mysql_fetch_array($sqlC)) {
$sqlCNextQuestion = $row["NextQuestion"];
}
}
//Find the question text pertaining to the ID of the next question that needs to be answered
$sqlD = mysql_query("SELECT QuestionText FROM Questions WHERE PKID = $sqlCNextQuestion");
//If the operation produces an error, output an error message
if (!$sqlD) {
die('Invalid query for SQLD: ' . mysql_error());
}
//Count the number of rows output
$sqlDCount = mysql_num_rows($sqlD);
//If rows exist, define the values
if ($sqlDCount > 0) {
while ($row = mysql_fetch_array($sqlD)) {
$SurveyStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyStartedQuestionText . '<br /><br />Answer Text Here';
//If the value for QuestionNumberReached is null, the user has not started the survey
} else if (empty($LastQuestionAnswered)) {
//Find the question text of the first question in the survey
$sql3 = mysql_query("SELECT QuestionText FROM Questions WHERE PKID IN (SELECT FirstQuestion FROM Batch WHERE BatchNumber IN (SELECT BatchNumber FROM User WHERE EmailAddress = '***'))");
//Count the number of rows output
$sql3Count = mysql_num_rows($sql3);
//If rows exist, define the values
if ($sql3Count > 0) {
while ($row = mysql_fetch_array($sql3)) {
$SurveyNotStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyNotStartedQuestionText . '<br /><br />Answer Text Here';
}
}
}
?>
HTML:
<body>
<?php
// Display the concatenated information that has been previously defined
echo $ToDisplay;
?>
</body>
This bit:
if ($StartedQueryCount > 0) {
probably evaluates to false, and there's no matching else tag that adds content.
Try changing:
}
?>
with:
}
else {
$ToDisplay = 'Error: no rows found to display!';
}
?>
Edit:
Also, this bit:
} else if (empty($LastQuestionAnswered)) {
Could be replaced with the more readable:
} else {
Since it does exactly the same thing.
And within your while loop, you are constantly redefining $ToDisplay, I assume this is wanted behaviour? Otherwise initialize the variable on top (before the while() loop) like so:
$ToDisplay = '';
And change the assignments within the loop to concatenations, like so:
$ToDisplay = 'text assignment';
To:
$ToDisplay .= 'text concat'; // look at the dot before =
Thank you for all your help! I really appreciate you all taking the time.
I finally realised what was wrong...
On Line 18 of my PHP code, I had the following:
while ($row = mysql_fetch_array($sql)) {
whereas it should of course have been this:
while ($row = mysql_fetch_array($StartedQuery)) {
Essentially I was calling the rows from the wrong query. And I feel a clot because of it!
Thanks again, everyone :)

getting number from php file with jquery ajax

I'm new to AJAX and jQuery. I'm trying to pass a number from unrate.php to be used as checkVal (as shown below). The file does a bunch of stuff but it only echos the number. When I add a alert(checkVal) it shows a invalid character and than the number I want. (I just want the number)...
ajax handler:
$.get("unrate.php?numb="+ID, function(checkVal){
if (checkVal == 1) {
number.innerHTML = addNumb + 1;
} else {
number.innerHTML = addNumb - 1;
}
});
unrate.php:
<?php
$uNum = $_SESSION['userNum'];
$ider = $_GET['numb'];
$sql = mysql_query("SELECT * FROM ratecheck WHERE ID =".$ider);
$checkRay = mysql_fetch_array($sql);
$checkVal = $checkRay[$uNum];
$sqlZ = mysql_query("UPDATE ratecheck SET `".$uNum."`=0 WHERE ID=".$ider)
or die(mysql_error());
$sqlB = mysql_query("SELECT * FROM sources WHERE ID =".$ider);
$sourceRay = mysql_fetch_array($sqlB);
$newRC = $sourceRay['ratecount'] - 1;
mysql_query("UPDATE sources SET ratecount =".$newRC." WHERE ID =".$ider)
or die(mysql_error());
if ($checkVal > 1)
{
$newpts = $sourceRay['points'] - 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] - 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
else
{
$newpts = $sourceRay['points'] + 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] + 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
echo $checkVal;
mysql_close();
?>
Extra characters at the beginning or end of your output are something you occasionally run into with php. I greatly endorse the comment that suggests looking at the raw output from the server. You might also want to think about these possibilities:
Invisible characters at the beginning or end of your script file. Use a text editor that will show you hidden characters (even a hex editor) and see if there are any. Also, you don't have to end your php script with ?> if you're not doing anything else past it. You can just leave it open, as that will prevent characters showing up at the end.
Check the character encoding that your script has. This might not be the solution, but some time ago I had a similar situation that went away when I changed the encoding to UTF8 without Byte-Order Mark. Try doing the same thing and see if that fixes it

How to match one ID from Multiple ID's?

I have this script below where it scans users that are allowed to see a post. How do i update it so that it will match the person viewing's ID to the one stored in the field. If it matches it works else it doesn't. The stored entries will be something like 99394david, 324234smith, 34343jane. So this script i have is not matching it.
$kit = mysql_real_escape_string($_GET['id']);
$sql="SELECT `Who_can_see` from `posts` where `post_id` = '$kit'";
$result=mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$userallowed = htmlspecialchars($row['who_can_see']);
}
}
//$personid is drawn from the database. its the id of the
person viewing the link.
if ( $userallowed == $personid ) {
echo("allowed");
} else {
echo("not allowed");
die();
}
?>
I would simply add the $personid to the query (although I have doubts about how you are filling your posts table exactly...):
$sql="SELECT `Who_can_see` from `posts`
where `post_id` = '$kit'
AND `Who_can_see` = '$personid'";
If your result contains a row, the user is allowed to view the post.
By the way, I would also recommend using prepared statements to avoid any potential sql injection problems.
Edit: Based on the fact that Who_can_see can contain a comma separated list of entries, you can use your original script, and just change how you match, using for example stripos.
if ( stripos($userallowed, $personid) !== false ) {
// $personid is found in $userallowed
echo("allowed");
} else {
echo("not allowed");
die();
}

Categories