I'm looking for a simple php script that will look through my database for a username and echo a column. The column I want to echo is a date.
I'm making a script that checks if the date assigned to the user is todays date.
$datenow = date("Y-m-d");
$user = $_SESSION['username'];
$connection = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database name');
$result = mysql_query("SELECT accessfrom FROM users WHERE username = $user");
// Now I need a simple way to check if the results date = $datenow(from above)
mysql_close(); //Make sure to close out the database connection
Don't use MySQL. It is deprecated. So, use mysqli_.
Presumably, username is a string. So, you have a mismatch in your comparisons. The naive solution is to add single quotes:
$result = mysql_query("SELECT accessfrom FROM users WHERE username = '$user'");
The correct solution is to use mysqli_ and use parameters for passing in values. This not only solves your problem. It also prevents SQL injection attacks, and teaches you how to correctly write queries.
First you should use pdo or something.
foreach($result as $v){
if ($v['date'] === $datenow){
//your have a hit
}
}
but you should do it in your query (where date = $datenow) or something
Related
I've got an update query running so that events in the database can be updated.
For example, the event record table :
Now, when I want to edit the record, I import all the current data from one and show it on a webpage, so that the user can edit the data, as shown:
However, if I submit that page and the event description is more than a few characters long it does not update at all. Here is my PHP/MySQL Code:
$event_title=$_POST['event_title'];
$event_desc=$_POST['event_desc'];
$event_date_start = $_POST['event_date_start'];
$event_date_end = $_POST['event_date_end'];
$db = mysql_select_db("millyaca_events", $connection);
mysql_query("UPDATE events set event_title='$event_title', event_desc='$event_desc', event_date_start='$event_date_start', event_date_end='$event_date_end' where unique_ID='$ID'", $connection);
Only just started learning PHP and MySQL so apologies if it's a really stupid mistake.
Here is the complete submit button script:
if (isset($_POST['submit'])) {
$ID = $_GET['ID'];
$event_title=$_POST['event_title'];
$event_desc=$_POST['event_desc'];
$event_date_start = $_POST['event_date_start'];
$event_date_end = $_POST['event_date_end'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "removed username", "removed password");
// Selecting Database
$db = mysql_select_db("millyaca_events", $connection);
// SQL query to fetch information of registerd users and finds user match.
mysql_query("UPDATE events set event_title='$event_title', event_desc='$event_desc', event_date_start='$event_date_start', event_date_end='$event_date_end' where unique_ID='$ID'", $connection);
mysql_close($connection); // Closing Connection
header("location: https://www.millyacademy.com/admin-zone/events_management/"); // Redirecting To Other Page
}
From the comments we've debugged this to being an apostraphe/quote in the data being passed to the query. To resolve this with your current DB driver use, mysql_real_escape_string, http://php.net/manual/en/function.mysql-real-escape-string.php.
You should switch to MySQLi or PDO though in the future and use prepared statements.
Here's a functional usage (untested, so maybe not functional?) using your current code.
if (isset($_POST['submit'])) {
$ID = (int)$_GET['ID']; //force this to an int, or you could also escape
$event_title= mysql_real_escape_string($_POST['event_title']);
$event_desc= mysql_real_escape_string($_POST['event_desc']);
$event_date_start = mysql_real_escape_string($_POST['event_date_start']);
$event_date_end = mysql_real_escape_string($_POST['event_date_end']);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "removed username", "removed password");
// Selecting Database
$db = mysql_select_db("millyaca_events", $connection);
// SQL query to fetch information of registerd users and finds user match.
mysql_query("UPDATE events set event_title='$event_title', event_desc='$event_desc', event_date_start='$event_date_start', event_date_end='$event_date_end' where unique_ID='$ID'", $connection);
mysql_close($connection); // Closing Connection
header("location: https://www.millyacademy.com/admin-zone/events_management/"); // Redirecting To Other Page
}
It is best to never pass user data directly to your queries.
Two Things.
Escape the data provided by user , that will take care of any quotation .
Ensure the db field you are trying to update has enough length.
Also it may be worth skipping the entire POST and do the update using hard coded values to see what is happening.
I am creating a login system for my website using a mysql database.
When the user registers, it saves the password to the database using:
$password = hash("sha512","somesalt".$password."moresalt");
Then when I login, I compare the password entered to the password in the database using the same hash function.
To compare the database I use this:
$query = mysql_query("select * from users where password='$password' AND email='$email'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {//do login stuff}
But rows always returns 0. When I remove the hash function from both the register and login, it logs in fine. What's wrong?
As a side note in case anyone's wondering, I would be using mysqli but my webhosting's database version is old. They are using 5.2 I believe.
I forgot to mention that I did check to make sure the database did match what it was getting as seen in these pics (can't embed pics so links):
https://drive.google.com/file/d/0B_u6weYp5wTCQng5eVhTSkZFRDg/view?usp=sharing
https://drive.google.com/file/d/0B_u6weYp5wTCQVRXTkNqdzhWUFE/view?usp=sharing
what is the length of your password field in database???
The reason seems to me is the hashed password length is too long and while saving to database part or it is dropped...
Then when you compare you get 0 rows...
Okay, I would like to suggest that you use prepared statements other than the mysql library. It is much more secure and reliable.
$query = "SELECT * FROM `users` WHERE AND `email`=:email_token";
Then you prepare and execute your query
$data = $connection->prepare($query);
try {
$data->bindParam(":email_token",$_POST["email"],PDO::PARAM_STR);
$data->execute();
}
$result = $data->fetch(PDO::FETCH_ASSOC);
while($row = $result) {
$out = $row["password"];
}
if($out == $_POST["password"]) {
//loggin
} else {
//get lost
}
This is a very basic structure but essentially you want to pull the password out of the database first then compare the strings instead of doing it all with your query.
I'd like to make an if statement that checks if the username, already exists in the MYSQL database. I tried some different stuff, but i cant make it work. Every time I test it in my browser I get a notice
Notice: Undefined index: username in etc.
I am confused if it has anything to do with the $result variable or the $check variable or neither.
Here is the HTML form and the PHP script.
https://gist.github.com/anonymous/9704354
Thank you and have a nice weekend!
There are a few things that are wrong in your code.
First, never place variables directly in SQL queries, thats how SQL injections happen. Start using PDO or another library for your MYSQL.
The reason you are getting an undefined notice is because of this line.
$result = mysql_query("SELECT * FROM users WHERE username = '$_POST[create_user]'");
It should be this without fixing the huge SQL Injection flaw
$result = mysql_query("SELECT * FROM users WHERE username = '{$_POST['create_user']}'");
Also you should add a "LIMIT 1" to the end of the select query to speed things up. No need looking for more than one user.
You can verify the user by just checking for row_count instead of checking the text values. Since MySQL is not case sensitive for some fields, username "AAAaaa" will be equal to "aaaAAA". If you check row count instead, you will be sure that no usernames are in the database of that text. Or if you want to check using PHP, make sure you pass the usernames through strtolower()
When you start using PDO, the following example will help you.
$dbh = new PDO() // Set the proper variables http://us2.php.net/pdo
if(empty($_POST['create_user'])) {
echo 'Username is Empty. Always check if POST and Get data is set';
die();
}
$query = "SELECT * FROM `users` WHERE `username` = ? LIMIT 1;"
$data = array($_POST['create_user']);
$sth = $dbh->prepare($query);
if(!$sth->execute($data)) {
echo 'Handle SQL Error';
die();
}
if($sth->rowCount() == 0) {
echo 'Unused Username';
}else{
echo 'Used Username';
}
This is what i've found
the $_POST['username'] should be like $_POST['create_user']
This register form was made by me, but it doesn't do what I want it to do.
I want it to connect to a mysql database and store the information that was given by the form. I want it to hash the $password in md5 and store it in the "gebruikers" table. Please don't reply with "Damn, you have no idea what you are doing" or something like that. I am learning PHP by looking to examples and following tutorials. Please keep in mind that the mysql insert code is not filled in right, because I got stuck a few lines above.
So, my question is: I want to check if the mysql table already contains $email. If it IS already in the mysql table, I want to display an error message that I can place somewhere else in my PHP page. If the email adress given is unique, than the $password should hash into md5 and store into the mysql database, just like the other form entries.
How do I do that?
<?php
// Fetching all the form details
$email = $_POST["email"];
$password = $_POST["password"];
$voornaam = $_POST["voornaam"];
$tussenvoegsel = $_POST["tussenvoegsel"];
$achternaam = $_POST["achternaam"];
$dag = $_POST["dag"];
$maand = $_POST["maand"];
$jaar = $_POST["voornaam"];
$straat = $_POST["straat"];
$postcode = $_POST["postcode"];
$woonplaats = $_POST["woonplaats"];
$cniveau = $_POST["cniveau"];
$oniveau = $_POST["oniveau"];
$voornaam = $_POST["voornaam"];
$aboutme = $_POST["aboutme"];
//Here's where I don't know how to continue
$check = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email'");
if($check === FALSE) {
//there is a user already registered
echo("$email is al in gebruik. <a href='login.php'>Inloggen</a>?");
} else {
//There isn't a username
//mysql_query("INSERT INTO `user` (`id` ,`username` ,`password`) VALUES (NULL , '{$_POST['email']}', MD5( '{$_POST['password']}' ))");
echo("You have been registered!");
}
P.S.: I'm not a native English speaker, so please ignore my grammar mistakes/typos.
First of all, you made a major mistake: There is a SQL-Injection security hole.
Please read this: http://php.net/manual/en/security.database.sql-injection.php
Second, you should use mysqli instead of mysql, because mysql is deprecated.
Your error is that SQL does only return false if the query is invalid, not if there are no results. So the correct way of checking if there are results is to use http://php.net/manual/en/mysqli-result.num-rows.php
$result = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email' LIMIT 1");
if(mysql_fetch_array($result) !== false)
{
...
} else {
....
}
You should also read up on preventing SQL injection.
Maybe you've forgot to set the mysql_connect statement.
But I strongly recommend you stick from now on, with the mysqli_ functionality, since, as Aragon0 said, mysql is deprecated in PHP's newest versions.
Besides, mysqli statements are simpler than the mysql ones, for example you use one statement (mysqli_connect) to connect to your host and select your database at the same time, instead of using separated statements (both mysql_connect and mysql_select_db).
Oh, and no additional service package is required to use it. :)
The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.