How can I make this script to where if it finds that the fname and lname do not exist that it will pop up a message saying that they never signed in.
<?php
session_start();
include_once("connect.php");
date_default_timezone_set("America/Winnipeg");
$date = ("m-d-Y");
$timeout = date("g:i:s a");
if ("SELECT EXISTS(
SELECT *
FROM signin_out
WHERE
lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "'
AND date='" . $date . "')"
) {
mysql_query("
UPDATE signin_out
SET timeout='" . $timeout . "'
WHERE
lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "'
AND timeout=''
");
header("Location: ../index.html");
} else {
echo "<script type='text/javascript>'";
echo "alert('<p>Oops! You never signed in!</p><br><p>Please contact a
Librarian</p>');'";
echo "</script>'";
header('Location: ../index.php?notsignedin');
}
?>
This is an intranet site for a highschool.
$sql = "SELECT COUNT(*) signedin FROM signin_out
WHERE lname = '" . mysql_real_escape_string($_POST['lastname']) . "'
AND fname = '" . mysql_real_escape_string($_POST['lastname']) . "'
AND date = '$date'";
$result mysql_query($sql) or die(myqsl_error());
$row = mysql_fetch_assoc($result);
if ($row['signedin'])) {
// update table
} else {
// Report not signed in
}
However, you really should switch to mysqli or PDO so you can use parametrized queries instead of concatenating strings, so you don't have to worry as much about escaping them.
This is only one part of the answer, #Barmar gave u how to handle the query itself.
Change
echo "<script type='text/javascript>'";
echo "alert('<p>Oops! You never signed in!</p><br><p>Please contact a
Librarian</p>');'";
echo "</script>'";
header('Location: ../index.php?notsignedin');
To
echo "<script type='text/javascript>'";
echo "alert('Oops!\nYou never signed in!\nPlease contact a
Librarian');'";
echo "window.location.href='../index.php?notsignedin';";
echo "</script>'";
The reason:
Strings which echo go into the web server buffer before being sent as a package to the browser.
This may cause your code to reach and do the header command, and then either you will redirect immediatly, or get an error message on the lines of '...you can not send headers after output...'
And seriously consider everybody's suggestion about PDO/Mysqli and using a more centralized/abstracted way to use the DB.
Check how many rows are returned by the query,if is more than 1 then fname and lname exists in database,you can also use count(*) but i won't to change your query :
$result = mysql_query("SELECT * FROM signin_out WHERE lname='".$_POST['lastname']."' AND fname='".$_POST['firstname']."' AND date='".$date);
$num_rows = mysql_num_rows($result);//count number of rows returned by query
if($num_rows >=1) {
//Update here
}
else {
//alert and redirect here
}
I understand that your site is for intranet use only , but i suggest to use PDO or Mysqli
Related
I need each row to have a unique button beside it which will delete the message. I need it to only be able to be deleted by the receiver. My first thought was to echo a HTML form inside the while loop. I don't think that would work though. If it does work what would the SQL statement inside if(isset()) look like? Each message has an ID so could I use that? If you need to see rest of the code let me know.
$Select = "
SELECT * FROM Messages
WHERE Receiver='$Identifier'
ORDER BY ID
DESC
LIMIT 10";
$Result = $Connect->query($Select);
if (mysqli_num_rows($Result) > 0) {
while ($Row = mysqli_fetch_assoc($Result)) {
echo nl2br("Sender = " . $Row["Sender"] . " Message = " . $Row["Message"] . "\n");
}
}
why don't try this:
echo "Sender = " . $Row["Sender"] . " Message = " . $Row["Message"] . "<button id=".$Row["ID"].">Delete</button>";
This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.
for some friends and family (different sites), I created a script that allows them to input data into the database. With
echo ("<a href=\"./pagina.php?ID=" . $row['ID'] . "\">" . $row['ID'] . "<br>");
, I 'send' the ID of the requested table to the URL.
In pagina.php, I have this code:
ID: <?php echo $_GET["ID"]; ?>
That works, of course, but now I want to use that ID to also display the data from the database, so not from the URL. These values are " . $row['onderwerp'] . " and " . $row['tekst'] . "
(There may be more values to come, but I'm just a beginner, trying to get something to work).
I know this is possible, but I just can't get anything to work, as I have just started learning PHP.
I hope you can help me.
If you don't care whether data came from a $_COOKIE, $_GET, or $_POST, you can use $_REQUEST.
$id = (int)$_GET['id'];
$sql = "SELECT onderwerp, tekst FROM yourtable WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo "{$row['onderwerp']} - {$row['tekst']}<br />";
}
This is my code for the update:
$key = $skills[$ind];
echo "\t\t<td>" . $key . "</td>\n";
//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];
echo "\t\t<td>" .$data_n[0] . "</td>\n";
echo "\t\t<td>" .$data_n[1] . "</td>\n";
echo "\t\t<td>" .$data_n[2] . "</td>\n";
$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
or
die(mysql_error());
Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:
UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'
There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.
All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.
1) You does not seem to have connected to mysql. Does your code do mysql_connect and mysql_select_db prior to this ?
2) Try running the query in the PHPMyAdmin (or whatever MySQL client you use) to see if there's any error or not. Does the query runs fine there ?
3) Most probably, there is no username with value derekboy in your table.
I don't know PHP particularly well, but it seems that you are surrounding the variables with single quotes, in which variables aren't interpolated.
Try something like:
$result = mysql_query("UPDATE accounts SET " . $key . " ='" . $data_n[1] . "' WHERE username = '". $user" . "'") or die(mysql_error());
about my system the university complaint..stud or staff can use this system to complaint.
first user fill the form complaint and submit after submit user can view the complaint.now the problem is the complaint can't display....
this code for user complaint(userCampus.php):
?php // ------------------------------------------------------PROCESS -------------------------- START. ?>
<?php
$page_title='userCampus';
if(isset($_POST['submit'])){
if($_POST['secname']){
//$sn=escape_data($_POST['secname']);
$sn=$_POST['secname'];
// echo '<br> sn is : ' . $sn;
}else{
$sn=FALSE;
$message .='<p>You forgot to select section name!</p>';
}
if($_POST['subject']){
//$s=escape_data($_POST['subject']);
$s=$_POST['subject'];
}else{
$s=FALSE;
$message .='<p>you forgot to enter subject!</p>';
}
if($_POST['comment']){
//$c=escape_data($_POST['comment']);
$c=$_POST['comment'];
}else{
$c=FALSE;
$message .='<p>you forgot to enter comment!</p>';
}
}
if($sn && $s && $c ){
$userid = $_SESSION['username'];
$groupid = $_SESSION['secname'];
$query=" INSERT INTO campuscomplaint (secname, subject, comment, nameuser, groupid, userid)" .
" VALUES (" . "'" . $sn . "','" . $s . "','" . $c . "','" . $nameuser . "','" . $groupid . "','" . $userid . "')";
//echo 'query is : ' . $query . '<br>';
include "connectioncomplaint.php";
mysql_query($query);
echo'<p><b></b></p>';
include('done.php');
exit();
}
?>
<?php //------------------------------------------------ PROCESS ------------------------------------ end. ?>
<form action="<?php echo$_SERVER['PHP_SELF'];?>" method="post">
this code for view the complaint-userView.php(use for other page):
<?php //======================================================================================================================= PROCESS DATA ======================================================= START.
include "connectioncomplaint.php";
?>
<?php
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
//echo 'test : ' . $subject;
//Tarik data dari sini
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
//echo 'QUERY DETAIL :' . $queryDetail . '<br>' ;
$resultDetail = mysql_query($queryDetail);
//echo 'RESULT DETAIL :' . $resultDetail + 0 . '<br>' ;
$detail = mysql_fetch_array($resultDetail);
//echo $detail . '<br>';
//echo 'detail subject is : ' . $detail['subject'] . '<br>';
//echo 'detail comment is : ' . $detail['comment'] . '<br>';
//echo $detail[$x] . '<br>';
?>
i hope u all can help me....becoz i zero php.......
Let's see if we can check everything in on snip of code:
Paste the debugging code right after the line:
$detail = mysql_fetch_array($resultDetail);
Debugging code:
echo '<pre>';
echo '$userid = '.$userid."\n";
echo '$secname = '.$secname."\n\n";
echo 'Query: '.$queryDetail."\n\n";
echo 'Query results:'."\n\n";
print_r($detail);
echo '</pre>';
die();
That should make it clear where your problem is.
Also you should understand why you need to use mysql_real_escape_string() It's very important to make sure people don't do bad things to your website. Never send anything that can be changed by the user (such as GET or POST data) straight to a database without at least using this function. This escapes characters that would otherwise allow them to change your query (making it do something you don't want). To learn more about this google "sql injection attack"
one thing, from my experience. if something wrong with your query, just try it on mysql. ran your query in sql, and instead of your variables put some values, so you can easaly see what is your problem.
Looks like you forgot a $ sign before secname and you don't sanitize variables going to the query. So, try make it this way:
<?php
include "connectioncomplaint.php";
$userid = mysql_real_escape_string($_GET['userid']);
$secname = mysql_real_escape_string($_GET['secname']);
//Tarik data dari sini
$queryDetail = "SELECT * FROM campuscomplaint " .
"WHERE userid = '$userid' AND secname = '$secname'";
$resultDetail = mysql_query($queryDetail) or trigger_error(mysql_error()." in ".$queryDetail);
$detail = mysql_fetch_array($resultDetail);
?>
It looks you're not using a primary key on your campuscomplaint table, and using the various data fields as the identifier.
Since you say the data's inserted fine, you have to look at how you're retrieving it:
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
and then using these as your WHERE clause in the SQL query:
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
For one, this is vulnerable to SQL injection, and any $subject or $comment that contains single quotes will break the query. You are not checking to see if the query succeeded by calling mysql_error() after the mysql_query() call.
Also consider that you're retrieving these record "identifiers" from a GET query. These do have a limited length (different for various browsers). What if someone's comment is 10 kilobytes of data, but the browser will only send 1024 characters? Even if the database query succeeds, it will return no data because the comment fields will never match.
Let's say that the query string is limited to 100 characters (just for example purposes). You generate a list of complaints that looks something like this:
View complaint
Now remember, our query string is limited to 32 characters, so when the user clicks on the link, this is what will be sent to the server:
GET http://www.example.com/viewcomplaint.php?userid=7&secname=12&subject=This class sucks!!!&comment=Who hired this professor? He doesn't know a
and you'll end up with the following "identifiers"
$userid= 7;
$secname = 12;
$subject = "This class sucks!!!";
$comment = "Who hired this professor? He doesn't know a";
Notice how the $comment has been cut off. It will never match what is stored in the database, so your retrieval query will fail. Furthermore, notice that there is a single quote in it (doesn't). Inserting $comment into your query verbatim will now cause an SQL syntax error because of the imbalanced single-quote.
Add an auto_incrementing primary key field to your campuscomplaint table, like this:
ALTER TABLE campuscomplaint ADD id int unsigned not null auto_increment primary key;
and then all your complains can be identified by a single number, and you can retrieve them like this:
$id = (int)$_GET['id']; // force $id to be a number. better than just blindly using the value in a query
$query = "SELECT * FROM campuscomplaint WHERE id = $id;";
$result = mysql_query($query);
if (mysql_error()) {
// did the query fail? Say why!
die("MySQL query failed! Error cause: " . mysql_error());
}
etc....
The use of a numeric identifier will easily keep your query string very short (unless the people registering complaints file so many you get up into numbers hundreds or thousands of digits long).