i'm making a small PHP application that uses some data to check whether it matches the records of the database or not(a prototype of a login process), but it gives me a (extra junk data error) and when commenting the header line to check the error it gives me that fatal error:
Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\hh\login.php on line 22
The Code:
<?php
header("Content-type: text/xml");
$host = "localhost";
$user = "muhammed";
$pass = "";
$database = "test";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$query = "SELECT * FROM info";
$resultID = mysql_query($query, $linkID) or die("Data not found.");
$name = "tahany";
$age = 90;
while(true){
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
if ($row['Name'] == $name && $row['age'] == $age){
$res = "login success";
break;
}else{
$res = "failed to login";
}
}
}
echo $res;
?>
You need to optimize your code, There is no need of extra for loop.
while($row=mysql_fetch_assoc($resultID)){
if ($row['Name'] == $name && $row['age'] == $age){
$res = "login success";
}else{
$res = "failed to login";
}
}
NOTE: mysql_* functions are deprecated move on mysqli_* functions asap.
You getting fatal error because of infinite loop you are putting break in inner loop but outer loop is infinite.
You can (and should) remove the while (true) statement from the code. It is not needed. This is what's causing your timeout. The break statement only breaks the inner for-loop and not the outer while loop.
Now, a fix for the while loop could be something like this:
$break_loop = false;
while (!$break_loop ) {
// Keep your existing code as-is.
for (...) {
if (...) {
...
} else {
...
}
}
// Always break the loop, whether or not the log-in was successful.
// We need to stop the while-loop anyhow.
//
// When the log-in was successful, we jumped out of the for-loop much
// sooner.
$break_loop = true;
}
So we use a temporary variable to keep the loop running until the variable is set to true. This happens when we jump out of the for-loop when the log-in is successful, or when all attempts failed.
But again, the while-loop is not needed because your for-loop handles it already.
it is not good to use this code but it is useful
break 2;
http://php.net/manual/en/control-structures.break.php
If you need to increase the time out of PHP Script. Do this
<?php
set_time_limit(0);
Actual problem lies here in your while loop.
Your while loop is running in a infinite condition. Try changing it like . Always remember while(true) runs infinitely.
$i=0;
while($i==0){
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
if ($row['Name'] == $name && $row['age'] == $age){
$res = "login success";
break;
}else{
$res = "failed to login";
}
}
$i=1; // Changing the flag to 1 , so while condition fails
}
Related
I am trying to store IP's in a MySQL database and I had a few problems with it which i was able to fix but i keep getting 1 error for people that trying to get onto my website. So when someone gets on my website their IP is displayed with a time stamp but it only works when I connect to my website. When I got my friend to go onto my website he got an error saying why u no query? which helps me find out where the problem is. Now the problem is that I have been trying to solve this issue for the past 2 hours with no luck :(
Screenshot of my screen: My screen
Screenshot of my friends screen: Friends screen
<html>
<head>
<title>Your IP!</title>
</head>
<body>
<?php
$db_host = '127.0.0.1';
$db_user = '***************';
$db_pwd = '*************';
$db = '***************';
// Find their IP and tell them what it is.
$con=mysqli_connect($db_host, $db_user, $db_pwd);
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pip = getenv('HTTP_X_FORWARDED_FOR');
$ip = getenv('REMOTE_ADDR');
echo "Your Proxy IP is: ".$pip."(via ".$ip.")";
} else {
$ip = getenv('REMOTE_ADDR');
echo "Your IP is: ".$ip;
}
echo "<br /><br />";
// Try to select the database.
if(!mysqli_select_db($con, $db)) {
// die("why u no use db? ".mysql_error());
die("why u no use db?");
}
// Try to perform query.
// This is a function so it may easily be called multiple times.
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
}
return $result; // Give back result.
}
// Try to see if they are in the database already,
// and if not, then add them.
$result = do_query("select ip from ips where ip='".$ip."'");
$rows = mysqli_num_rows($result);
if($rows == 0) {
do_query("insert into ips (ip) values ('".$ip."')");
}
// Now, display the table.
$result = do_query("select * from ips");
$cols = mysqli_num_fields($result);
echo "<table cellpadding=\"5\" bgcolor=\"#7F7F7F\"><tr>";
for($i = 0; $i < $cols; $i++) {
echo "<td>".mysqli_fetch_field($result)->name."</td>";
}
echo "</tr>";
while($row = mysqli_fetch_row($result)) {
echo "<tr>";
for($i = 0; $i < $cols; $i++) {
if($row[$i] == $ip) { // bold their IP.
echo "<td><b>".$row[$i]."</b></td>";
} else {
echo "<td>".$row[$i]."</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
So first I changed
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
to
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die(mysqli_error($con));
Which showed me the error which was Duplicate entry '0' for key 'PRIMARY' and the problem was that I did not set AUTO_INCREMENT on the Primary key.
I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?
I am using the header function to locate to another page based on certain conditions. I am monitoring a mailbox and the code redirects to another page based on the sender address. All headers are working except one. If the sender does not belongs to any existing group, I wanted to redirect it to new.php. But it is not redirecting. I am unable to figure out why. Please help me.
<?php
session_start();
$server = '{server}INBOX';
$username = 'aaa#bbb.com';
$password = 'password';
require_once '../swift/lib/swift_required.php';
include('connection.php');
$connection = imap_open($server,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$_SESSION['connection']=$connection;
$result = imap_search($connection,'UNSEEN');
if($result) {
rsort($result);
foreach($result as $email_number)
{
$header = imap_headerinfo($connection, $email_number);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$query = "select * from usergroup where email='$fromaddr'";
$_SESSION['fromaddr']=$fromaddr;
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
$email=$line['email'];
$group=$line['group'];
if(mysql_num_rows($result1) == 1){
if($group == 1){
header("Location: facilitator.php");
}
elseif($group == 2){
header("Location: learner.php");
}
}
elseif (mysql_num_rows($result1) == 0) {
header("Location: new.php");
}
}
}
}
elseif (!$result)
{
echo "No unread messages found";
}
?>
It appears as though you are nesting that redirection inside the while loop. Since there are no rows, the while condition mysql_fetch_array() will immediately return FALSE and skip the whole block, including the redirection you intended it to follow.
Move the test for mysql_num_rows() outside the while loop.
// Test for rows and redirect BEFORE entering the while loop.
if (mysql_num_rows($result1) === 0) {
header("Location: new.php");
// Always explicitly call exit() after a redirection header!
exit();
}
// Otherwise, there are rows so loop them.
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
$email=$line['email'];
$group=$line['group'];
if($group == 1){
header("Location: facilitator.php");
}
}
You actually may not need a while loop at all, depending on how many rows you are expecting to fetch. If you only expect one group per email, then forego the loop and just call $line = mysql_fetch_array() once. However, if you are expecting multiple rows but want to redirect on the first one encountered where $group == 1, then your logic works. In that case however, since you are only doing the redirection and no other action, you might as well just put that condition in your query:
// Test the group in your query in the first place.
$query = "select * from usergroup where email='$fromaddr' AND group = 1";
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());
if (mysql_num_rows($result1) === 0) {
// you didn't match a row, redirect to new.php
}
else {
// you had a match, redirect to facilitator.php
}
Easy one:
change:
elseif (mysql_num_rows($result1) == 0){
to:
else {
The condition in the else if is probably false - so you don't get in there and thus the redirection doesn't occur.
can some one point out the problem with this code? It supposed to fetch data from mysql but it returns blank. Here is the full code.
<ul class="list">
<?php
require("object/db.class.php");
error_reporting(0);
function entry_tickets() {
if($_SESSION['dojopress_global:root'] == false) {
$entry_ticket .= <<<ENTRY_TICKET
<li><p><img src="http://cdn1.iconfinder.com/data/icons/humano2/32x32/apps/gnome-keyring-manager.png" />Access denied</p></li>
ENTRY_TICKET;
} elseif($_SESSION['dojopress_global:root'] == true) {
$q = "SELECT * FROM `notice` ORDER BY nid LIMIT 12 DESC";
$r = mysql_query($q);
if ( mysql_num_rows($r) == 0 ) {
$entry_ticket .= <<<ENTRY_TICKET
<li><p><img src="http://cdn1.iconfinder.com/data/icons/humano2/32x32/status/dialog-information.png" /> Nothing to display</p></li>
ENTRY_TICKET;
} elseif ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_array($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
function note_type($type) {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return ($type);
}
$entry_ticket .= <<<ENTRY_TICKET
<li><p> $athor, note_type($type)</p></li>
ENTRY_TICKET;
return $entry_ticket;
}
}
}
}
echo entry_tickets();
?>
</ul>
<div style="clear:both;height:10px;"></div>
sorry forgot db.class.php
<?php
session_start();
//connect.php
$host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "au";
$connectClass = mysql_connect("$host", "$db_user", "$db_pass") or die ("Couldn't establish connection to database server.");
$dbObject = mysql_select_db("$db_name", $connectClass) or die ("Couldn't select database.");
?>
error reporting disabled error code
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\wamp\www\ageis\note.php on line 22
Your mysql syntax looks bad. You have:
SELECT * FROM `notice` ORDER BY nid LIMIT 12 DESC
try
SELECT * FROM `notice` ORDER BY nid DESC LIMIT 12
Erik's comments should have pointed you in the right direction, however:
Figure out where PHP logs errors. Either turn up php's error reporting level so you see more errors, or start tailing your apache error_log
You should always check for errors after running mysql_query and do some sort of logging on failure. This is probably best accomplished by writing a wrapper function for mysql_query that does this, or using a 3rd party db wrapper that has already solved this problem.
You're redefining function note_type every time through your while loop. You have a return call outside the function, below it. Really I can't see how this is even syntactically correct. It looks like you have a large problem with mismatched brackets.
As for an actual database issue, you should check mysql_error() if no rows return from the call because it's likely something went wrong.
Also I recommend using PDO which is a true database class instead of the native function based ones.
Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}