I'm using mysql and php for registration on my web-site. Registration is ok. Mysql do queries immediately. But in login there strange things begin to happen. I insert a test in my php code to insert test row to database. First test code inserted immediately, but 2nd was inserted after series of refresh and relog actions only after 10 minutes. The 3rd test query is the same-after approximately 10 minutes after 2nd query.
Here is login code:
<?php
session_start();
if(isset($_SESSION['id'])){
echo 'You have logged in.';
echo $_SESSION['id'];
}
else {
$email=$_POST['email'];
$password=$_POST['password'];
$db=new mysqli('','','','');
if (mysqli_connect_errno()) {
echo 'Unable to connect to database: '.mysqli_connect_error().'. Please e- mail our system administrator. We will fix this error as soon as possible. Thanks for patience and understanding. ';
exit();
}
//TEST QUERY
$query="insert into test values(3, 'test')";
$result=$db->query($query);
//LOGIN QUERY
$query="select id from users where email='$email' and password='$password'";
$result=$db->query($query);
if ($result->num_rows==0) {
echo 'Incorrect email or password.';
}
else {
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
echo 'You have logged in.';
echo $_SESSION['id'];
//THIS TEST QUERY IS NOT IMPLEMENTED
$query="insert into test values(1, test)";
$result=$db->query($query);
}
}
?>
Where is mistake?
Test table consists of 2 columns: id (medium int, primary key, unsigned) and test(text)
Thanks in advance.
Sounds like the cookie could be expiring after 10 minutes. Run echo session_cache_expire(); to see what your expiration time is set to. More details at http://php.net/manual/en/ref.session.php
insert into test values(1, test)
-- test -- needs quotes or you are going to get an error that the column test doesn't exist (unless it does). If it does exist, it's probably going to be empty, as mysql probably doesn't know what you mean by test -- maybe your version thinks it's a constant or something.
If you posted what the table structure of your test table is, that would help solve it probably.
This looks suspicious to me.
$query="insert into test values(3, 'test')";
Is it trying to set the ID of every row inserted to 3? ID's have gotta be unique.
EDIT:
This probably won't fix your problem, but it will make your life easier by not forcing you to manually change ID's each time.
INSERT INTO test SET <colname>='test'
where <colname> is the name of the column that "test" is going into.
Just a little security hint: your SQL queries are very dangerous as they are prone to SQL injection attacks. See the Wikipedia article for alternatives ...
Related
I am currently looking to run a basic insert query using PHP to submit HTML form data to MySQL database.
Unfortunately however the insert process isnt running.
In my Insert syntax I have tried including $_POST[fieldname], ive tried including variables as below, and ive even played around with different apostrphes but nothing seems to be working.
as a side dish, im also getting truck load of wamp deprication errors which is overwhelming, ive disabled in php.ini and php for apache.ini file and still coming up.
If anyone can advise what is wrong with my insert and anything else id be much thankful.
Ill keep this intro straightfoward.
Person logs in, if they try to get in without login they go back to login page to login.
I connect to database using external config file to save me updating in 50 places when hosting elsewhere.
Config file is working fine so not shown below.
database is called mydb.
Im storing the text field items into variables, then using the variables in the insert query.
unitID is an auto increment field so I leave that blank when running the insert.
Unfortunately nothing is going in to the mysql database.
Thanks in advance.
PS the text fieldnames are all correctly matched up
<?php
//Start the session
session_start();
//check the user is logged in
if (!(isset($_SESSION['Username']) )) {
header ("Location: LoginPage.php?i=1");
exit();
}
//Connect to the database
include 'config.php';
$UserName = $_SESSION['Username'];
$UserIdentification = $_SESSION['UserID'];
if(isset($_GET['i'])){
if($_GET['i'] == '1'){
$tblName="sightings";
//Form Values into store
$loco =$_POST['txtloco'];
$where =$_POST['txtwhere'];
$when =$_POST['txtdate'];
$time =$_POST['txttime'];
$origin =$_POST['txtorigin'];
$dest =$_POST['txtdest'];
$headcode =$_POST['txtheadcode'];
$sql= "INSERT INTO sightings (unitID, Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('','$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
mysql_select_db('mydb');
$result=mysql_query($sql, $db);
if($result){
$allocationsuccess = "Save Successful";
header ('Refresh: 2; url= create.php');
}
else {
$allocationsuccess = "The submission failed :(";
}
}
}
?>
"unitID is an auto increment field so I leave that blank when running
the insert"
That's not how it works. You have to omit it completely from the INSERT statement. The code thinks you're trying to set that field to a blank string, which is not allowed.
$sql= "INSERT INTO sightings (Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
should fix that particular issue. MySQL will generate a value automatically for the field and insert it for you when it creates the row.
If your code had been logging the message produced by mysql_error() whenever mysql_query() returns false then you'd have seen an error being generated by your query, which might have given you a clue as to what was happening.
P.S. As mentioned in the comments, you need to re-write your code with a newer mysql code library and better techniques including parameterisation, to avoid the various vulnerabilities you're currently exposed to.
So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote
I have created a form in HTML and the action is set to a php script. I'm pretty new to php and was wondering if someone could help me out with it? I need to write a script to add the info from the form to a database. I need to create the database and the table as well. I did a lot of reading on the net and I'm still unable to do it. This is the script I have. Please tell me what mistakes I have made. Thank you for all the help.
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
$sql="CREATE DATABASE user";
if (mysql_query($con,$sql)) {
echo "Database user created successfully";
}
$sql="CREATE TABLE Persons(PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID),firstName CHAR(30),lastName CHAR(30),age INT, dateofbirth DATE, email CHAR(30)";
if (mysql_query($con,$sql)) {
echo "connected to database";
}
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
if (mysql_query($con,$sql)) {
echo "added to database";
}
mysql_close($con);
?>
I tried all the suggested answers and still not able to do it. Can someone please provide the code to do that? I need to obtain data from a form and insert it into a database using php!
Hi Try This Code,
$con=mysql_connect("example.com","peter","abc123");
$sql="CREATE DATABASE user";
if (mysql_query($sql))
{
echo "Database user created successfully";
}
1.- Don't use mysql_ functions because are deprecated, use mysqli_ functions or PDO instead.
2.- You have several error i guess, first of all you select a database my_db on the connection script, but you are created another database in the next line... it's very strange this behaviour. If this script executes every time then you should change your code (you can't create a database and a table every time.
In the insert string you have an error with the post code, try this:
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}','{$_POST['dateofbirth']}','{$_POST['email']}')";
Your CREATE TABLE query will fail because of syntax error. You have to check queries results especially when next query depends on previous (and you're doing operations like creating databases/tables).
Next thing to change is mysql_*. This functions are deprecated and instead you should use PDO or mysqli_* (they are not hard to learn, just try).
And one more important change have to be done in your script. You're getting user input and adding it to query. Don't do that! You have to always assume that user is trying to hack you, so all inputed data have to be checked and filtered. Also it's good to use prepared statements with such data.
if (mysql_query($con,$sql)){
echo "Database user created successfully";
} else {
echo 'Error creating database - ' . mysql_error();
}
Same thing for all your sql statements to see where you went wrong
Change your code (mysql_query($sql)) instead of (mysql_query($con,$sql))
Okay, I can post the PHP code if needed but I'm trying to use some data in my database, but have no idea how I can access it. It might be an easy reply but I'm new to this game...
Basically, I have been able to set up a login system for my site, where if you log in, it will display the logged in user's username, this is done through the use of $_SESSION and a session class.
Where if the user is logged in ($session->logged_in) etc
<h3>Welcome <? echo $session->username?> </h3>
</head>
<body>
<p> Welcome to the website, your details are below </p>
</body>
<?php } ?>
I return the user's username as such.
However, I can only currently access data from the table 'users', and 'users' is connected through foreign keys to a table called 'passengers' through the 'username' field.
What I would like to do, is instead of printing the username, print the user's surname.
So essentially it is like:-
Logging in sets up a session and recognises the username that is logged in.
By querying this username in a different table, can pull up data from all corresponding tables in the database.
But I have no idea how to go about it..
If you guys and girls know of any sample code, or could point me in the right direction that'd be fantastic.
<? php
mysql_connect("localhost", "username", "password");
mysql_select_db("databasename");
$query = "SELECT surname FROM passengers WHERE username = " . $session->username . "";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo "Hello, your lastname is $data";
?>
I think this is what you are referring to?
Also, even though you're new at php etc., try looking into mysql injection and how to prevent it (this current code is very susceptible to mysql injection -- if it were to use user input; thanks to Carrie Kendall lol =])
Good place to start is by using mysql_real_escape_string.
edit-
Not sure but this might also help out as I'm not entirely sure what you mean; mysql (left) join
Im making a registration script for my site and i want to check if $_POST['username'] does already exist in db.
Is there a better, less code way of doing it? I do the same for email.
This is how it looks like now:
$checkusername = mysql_query("SELECT username FROM users WHERE username = '$_POST[username]'");
$row83 = mysql_fetch_assoc($checkusername);
if ($_POST['username'] == $row83['username']) die('Username already in use.');
Add a unique constraint onto your table:
alter table users
add unique (username)
Then, your insert or update statements will fail out:
mysql_query("insert into users (username) values ('$username')")
or die('Username exists');
Of course, a bigger issue with your code is that you aren't preventing SQL injection. Your code should be:
$username = mysql_real_escape_string($_POST['username']);
mysql_query("insert into users (username) values ('$username')")
or die('Username exists');
since you are already checking the username in the sql call, then you really just need to see if a record is returned in the php side of things
$row83 = mysql_query($checkusername);
if (mysql_num_rows($row83) == 0) die('Username already in use.');
If you set username as "unique" in your database you can just go ahead and run the insert query, which will fail (which you can handle). The same goes for email - make it "unique".
This may come in handy.