How to use javascript to prompt based on room availability? - php

I'm new to programming and I need help on my code. I want my page to prompt me if there will be available rooms left. I'm using the onload function on the admin page.
so far here is my code
function prompt()
{
< ?php
include("dbconfig.php");
$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
?>
if(< ?php $result <= 14 ?>){
alert("Rooms left: < ?php echo $result ?>");
}
else{
alert("Welcome Admin.");
}
}
window.onload=prompt;
edit:
The code worked fine now but it displays "Resource id#4", not the value of the count.

I feel you can't mix php with js codes.
php is mainly on server side , while the js is client side
from the snippet you provide, maybe you should use purely php as follows:
< ?php
include("dbconfig.php");
$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
if ($result <= 14) {
echo("Rooms left: $result");
}
else {
echo("Welcome Admin.")
}
?>
This should be run at the first when request

I think you are confused about where PHP processes vs. where Javascript processes.
PHP is processed on the server side, while Javascript is processed on the client side. Think of it like this...
You access a page.
Your PHP is processed, and the final output is sent to the browser.
Your Javascript is processed by the browser.
As you have it now, you'd be getting some funny output... especially because of your lack of echo statements. Here is what you'd probably be seeing in your browser page source:
function prompt()
{
if(){
alert("Rooms left: < ?php echo $result ?>");
}
else{
alert("Welcome Admin.");
}
}
window.onload=prompt;
Notice the empty if statement (also the space in the start tags:
if(<?php echo ($result <= 14); ?>){
alert("Rooms left: <?php echo $result ?>");
}
This should make your Javascript evaluate a boolean true/false. Don't forget that Javascript needs to be wrapped in a < script > tag too!
To answer your MySQL question...
Try it like this:
//We can alias the COUNT(*) as MyCount for easy reference
$sql = "SELECT COUNT(*) as MyCount FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
$row = mysql_fetch_array($result); //$row is now an array and will now have your count in it
echo $row['MyCount']; //This will print the count from the database. You could use it in other ways as well.

mysql_query returns resource, not a result.
Try to use:
$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = #mysql_query($sql) or die('Could not execute query');
$count = mysql_result($res, 0, 0);

There should be no space in php tags:
< ?php
^
Should be:
<?php
You are also missing a fetching function, here is how you can get row count in a variable:
<?php $count = mysql_num_rows($result);?>
Later you can use the $count variable in the if condition.

use mysql_fetch_row , and after that in the condition , compare to $row[0]
$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = #mysql_query($sql) or die('Could not execute query');
$row = mysql_fetch_row($res);
if(< ?php $row[0] <= 14 ?>){

Related

PHP ADODB - Reuse Query Result?

How does one reuse a query result with PHP ADODB, at the moment I am doing this, which I assume is inefficient? :
$query = "SELECT colname FROM table";
$result1 = $db->SelectLimit($query,10,-1);
$result2 = $db->SelectLimit($query,10,-1);
// 1ST RUN
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result1->MoveNext();
}
// 2ND RUN
while (!$result2->EOF) {
echo $result2->Fields('colname').'<br>';
$result2->MoveNext();
}
To answer my own question, need to use:
$result1->move(0);
so like this:
$query = "SELECT colname FROM table";
$result1 = $db->SelectLimit($query,10,-1);
// 1ST RUN
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result1->MoveNext();
}
// 2ND RUN
$result1->move(0); // move recordset cursor back to 0
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result2->MoveNext();
}

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

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

send php text output to client browser and run rest in server side

I have a straight forward php script thats performs one mysql query. Based on this i then run about 10 more mysql queries. I then return the result via echo to the client.
But to save time for the client I can echo the result out THEN run the remaining 10 mysql queries server side so the client gets a quicker response.
can this be done? or does the client have to wait for the entire php script to executed server side before getting a text response?
Heres my code:
$dbc = mysql_connect("$db_host","$db_username","$db_pass");
if (!$dbc) { die('SERVER ERROR PLEASE CONTACT US FOR MORE INFORMATION!'); }
mysql_select_db("$db_name", $dbc);
$sql = "SELECT * FROM `ads` WHERE (`status` LIKE 'active%' OR `status` LIKE 'featured%') ORDER BY `clicks` DESC LIMIT 10;";
$result = mysql_query($sql,$dbc);
$totalads=mysql_num_rows($result);
$str="";
while ($row = mysql_fetch_assoc($result))
{
$str .= $row["banner"] . "][". $row["link"] . "<BR>";
//the code below is used to update stats but can be run after output to client
$views=$row["views"]; $targetviews=$row["targetviews"];
if (intval($views)+1 >= intval($targetviews))
{
$sql1 = "UPDATE `ads` SET `views` = `views` + 1 , `status` = 'expired' WHERE `ID`=".$row["id"].";";
}
else
{
$sql1 = "UPDATE `ads` SET `views` = `views` + 1 WHERE `ID`=".$row["id"].";";
}
$result2 = mysql_query($sql1,$dbc);
mysql_free_result($result2);
}
$str=rtrim($str,"<BR>");
mysql_free_result($result);
mysql_close($dbc);
die ($str);
What you want is completely possible with the use of ob_start(); Take a look here... http://www.php.net/ob_start and that will give you an idea. I don't know what your code looks like but as an example you could do something like this...
<?php
ob_start();
$query = "SELECT * FROM users";
$results = DB::get()->query($sql);
echo "<pre>";
print_r($results);
echo "</pre>";
$content = ob_get_content();
#ob_end_clean();
echo $contents;
//continue processing
obviously you need to tailor that for your specific script but that is an idea to get you where you need to go
~~~~~~~~~EDIT~~~~~~~~~~~~~
OK so using your code and comments here you go.
First, yes you can do more than one while loop with the results, though you shouldn't as that is bad coding practices.
That being said here is what I would do...
ob_start();
$level = ob_get_level();
$dbc = mysql_connect("$db_host","$db_username","$db_pass");
if (!$dbc) {
die('SERVER ERROR PLEASE CONTACT US FOR MORE INFORMATION!');
}
mysql_select_db("$db_name", $dbc);
$sql = "SELECT * FROM `ads`
WHERE (`status` LIKE 'active%' OR `status` LIKE 'featured%')
ORDER BY `clicks` DESC LIMIT 10;";
$result = mysql_query($sql,$dbc);
$totalads=mysql_num_rows($result);
$str="";
while ($row = mysql_fetch_assoc($result)) {
$str .= $row["banner"] . "][". $row["link"] . "<br />";
$views[] = $row['views'];
$target_views[] = $row['targetviews'];
$ids[] = $row['id'];
}
echo $str;
$content = ob_get_contents();
if(ob_get_level() > $level + 1) {
ob_end_flush();
}
echo $content;
#ob_end_clean();
for($i = 0, $len = count($views); $i < $len; $i++) {
if((intval($views[$i] + 1) >= intval($target_views[$i]) {
$sql = "UPDATE `ads`
SET `views` = `views` + 1 ,
`status` = 'expired'
WHERE `ID`=".$ids[$i].";";
} else {
$sql = "UPDATE `ads`
SET `views` = `views` + 1
WHERE `ID`=".$ids[$i].";";
}
$result = mysql_query($sql);
mysql_free_result($result);
}
//I don't know what this stuff here is for except for the close line, but it's her if you want it
$str=rtrim($str,"<BR>");
mysql_free_result($result);
mysql_close($dbc);
die ($str);
?>
You no longer need the die statement there, but I left it incase you wanted it for something else. That should do what you need, check my stuff for typos though I just kinda pushed it out real quick for ya. please don't forget to mark that little check box for the right answer if it works, or leads you to the solution. Thanks man
You can as example run the first query.
Then return data to client.
From client run the 2°nd ajax call that will call a php page with the second script, etc....
Maybe the 2°nd ajax can call a php page that will launch the other 9 queries and then finally get the last reply needed.
generate output string
flush it
and do less of code
http://www.php.net/manual/en/function.flush.php
I'm guessing that you're creating a website. So, you can run the 10 others queries in a AJAX call, launch at the loading of the page.
Your architecture will be:
main.php which run 1 query and return the HTML page with data of the query ;
long_query.php which run the other queries in background ;
page.html which present first query results and with some javascript called the long_query.php script to get the result of other queries.
You need for this to write some javascript which will run an AJAX call, get the data and modify the current HTML page to add the data returned. If you're already using jQuery on your project, you can use jQuery.ajax() function.

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/MySQL Count() Issue

I am trying to create a class registration system for a client that utilizes PHP and MySQL. I have the database and table all set up and that part works just fine, however, the client has requested that upon registration, if there are 3 or fewer students enrolled to warn that the class may not run.
I'm trying to use the count() function as well as passing a dynamic variable from a cookie, set from the registration PHP script. However, I've hit a roadblock. I can't seem to get the count() function to actually count the rows. My select statement is below. Any help would be greatly appreciated.
$class = $_COOKIE["class"];
$min_check = "SELECT class_list, COUNT(class_list) as count
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING count < 20";
$result = mysql_query($min_check);
$count = mysql_num_rows($result);
if ($count < 4)
{
echo "IF THERE ARE 3 OR FEWER PEOPLE SIGNED UP FOR THIS CLASS, IT MAY NOT RUN.\n";
echo "THERE ARE CURRENTLY " . $count . " PEOPLE SIGNED UP.\n";
}
else if ($count > 4)
{
echo "There are currently " . $count . " people signed up for this class.";
}
?>
Your SQL query is returning a list of the class_list values, along with a count of each specific instance, where there are less than 20 people registered.
$count = mysql_num_rows($result);
...is getting the number of records returned in the resultset, not the alias count value, which is why you aren't seeing the output you expect. You need to read into your resultset to get the value:
while ($row = mysql_fetch_assoc($result)) {
$count = $row['count'];
if($count < 4) { ... }
}
The count that you want is returned in the row of the query. the mysql_num_rows will count the rows returned, which is not what you want. Use this instead.
$result = mysql_query($min_check);
$count = mysql_fetch_row($result);
$count = $count[0];
On a first glance, the HAVING count < 20 is unnecessary.
You use the MySQL-count-function, but never retrieve it's value!? Use:
$firstRow = mysql_fetch_row($result);
$count = $firstRow[1]; // 1 indicates the second column (0 being the first)
I don't recommend using known MySQL identifiers like count. It's confusing.
$class = mysql_real_escape_string($_COOKIE["class"]);
$min_check = "SELECT class_list, COUNT(class_list) as mycount
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING mycount < 20";
Don't forget to escape the contents of that cookie!
The error is that count is a reserved word. You need to either surround it in backticks `count` or even better, use a different moniker. It's not an error per se, but it's just too confusing.
Next up, you are not actually retrieving the mycount result from the database. I suggest using code something like this:
$result = mysql_query($min_check);
while( $row = mysql_fetch_assoc($result) ) {
$people_count = $row['mycount'];
if ($people_count < 4) { echo "this" }
else { echo "that" }
}

Categories