I am having an issue with connecting my PHP script to the database on my localhost server.
I have posted the code below, it is to enable user registration on the site.
The input boxes appear as they should when I run the code, but nothing updates to the database when I try and complete a sign up.
As a novice with PHP I don't know enough about it to spot any errors I might be making, or what they mean.
Any help on this subject would be appreciated as there is a lot of info about PHP online, but I would rather know what was causing this error in order to prevent it in the future.
Here are the errors appearing in the browser console:
Failed to load resource: the server responded with a status of 404 (Not Found)
ReferenceError: Can't find variable: $
And the UNIX socket code from MAMP (I don't know where this would fit in):
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
And the PHP code:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
if (isset($_POST['register_btn'])) {
session_start();
$username =mysql_real_escape_string($_post['username']);
$email =mysql_real_escape_string($_post['email']);
$password =mysql_real_escape_string($_post['password']);
$password2 =mysql_real_escape_string($_post['password2']);
if ($password == $password2) {
//create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
}else{
$_SESSION['message'] = "Your passwords must match to proceed";
}
}
?>
Where to start? So many problems.
First off, you are using the OLD mysql functions which have been removed entirely in recent versions of PHP. Use the mysqli functions instead. The old functions like mysql_connect and mysql_query have been deprecated. You need to look for all occurrences of mysql_ in this code and think about replacing each command with its new counterpart.
You define this code to connect:
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
and then you don't use the resulting connection -- even check if it worked. You should always check the value returned by mysqli_connect to see if it actually worked or if it returned FALSE. You reconnect again and don't bother checking to see if it worked:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
And in doing so, you redefine $db to something else.
Also, you run a query without checking whether it succeeded or not:
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
You should be checking the result of mysqli_query (not mysql_query as you have in your code) to see what it returned. It should be TRUE if the INSERT query worked.
And after you redirect, you fail to call exit, which means that all the code that follows your redirect attempt may end up actually executing anyway.
Related
I've looked through StackOverflow for an answer to this and have so far come up empty handed. I know some have had a similar issue, but so far none of the responses to the issues have worked.
So I work on two sites, both of which are on the same host with the same PHP Admin set up (different accounts and domains, sites are not affiliated). One of them uses MySqli perfectly, without issues, while the other either gives a database selection failure, localhost access denied with password as "NO" or a blank page when I attempt to replace the MySql with MySqli.
The deprecated code:
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = #mysql_connect($host,$usr,$pwd);
if(!$connection){
die("No connection.");
}
mysql_select_db($dbname,$connection);
The MySqli I am attempting (identical to the site that MySqli works perfectly on):
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = mysqli_connect($host,$usr,$pwd);
if (!$connection) {
die("No connection.");
}
$db_select = mysqli_select_db($connection, $dbname);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
So the PHP error codes did not work at all and it had nothing to do with the local host or port, so I first checked to make sure mysqli_connect was on. Next, I ran a simple test where I echoed a random word before each mysqli command.
echo 'Passed.';
global $c_mysqli;
$conn = new mysqli($host, $usr, $pwd, $dbname);
echo '<br>Passed global mysqli.';
I found that my second pass was not working, and then proceeded to do an error message. An error showed up then. However, nothing I did fixed the issue... then I realized that one of my files, the header file, is the meat and potatoes and if it were to fail then everything else would fail too.
Sure enough, one of my lines of code contained a mysql connection and not mysqli. Long story short, double check and triple check to make sure that all
$statement = mysql_query("STATEMENT");
$query = mysql_fetch_array($statement);
Appear as
$statement = $conn->query("STATEMENT");
$query = mysqli_fetch_array($statement);
So I'm checking whether the person accessing the page is a user then redirecting them to the signup page if they're not.
Then I'm checking whether the user is a member ( paid subscription ) if not then redirect to the user page.
The redirecting for the non users work
But with the code below, noone can get access to the membership page because of the is_member check
<?php
error_reporting(0);
session_start();
include('connect.php');
ob_start();
if(!isset($_SESSION['username']))
{
header("**********");
}
else
{
$username =$_SESSION['username'] ;
}
$check = $mysqli->query("SELECT is_Member FROM users WHERE username = $username");
$row = mysql_fetch_assoc($check);
$isMember = $row['is_member'];
if ($isMember == 0){
header("*************");
}
is_member is either a 1 or a 0: 1 meaning they are a member
Connect file:
<?php
$servername = "*****";
$user = "*****";
$password = "*****";
$dbname = "******";
$mysqli = new mysqli($servername, $user, $password, $dbname); //used to connect to the database
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
?>
This
WHERE username = $username");
If the variable is a string (i.e.: "john", then it should be wrapped in quotes:
WHERE username = '$username'");
Then you're using a mysql_ function mysql_fetch_assoc which does not intermix with any other MySQL API than its own.
It must read as mysqli_fetch_assoc with the added i for the function.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
You should also add exit; after each header, otherwise you code may want to continue executing.
Another thing; your code is prone to an SQL injection. It's best that you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
It appears that your check will always come up false because there is not is_member value, it is a typo. Replace this:
$isMember = $row['is_member'];
with this:
$isMember = $row['is_Member'];
Also your else statement should probably include more
Im trying to create a login for my website and i need to store emails, usernames, passwords, ect in a database i have created already using phpMyAdmin. I have gone through article after article and nothing seems to be working. i have my connect.php like this:
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
mysql_connect($hostname, $username, $password) or die("Cannot connect to server");
mysql_select_db($databaseName) or die("Cannot select database");
?>
And my main.php like this:
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
?>
And i have created a simple form in my html like this:
<html>
<head></head>
<body>
<form>
<input type = "submit" action = "main.php" method = "post" value = "Login">
</form>
</body>
</html>
After submitting the form it says cannot connect to server. I am new to php and mysql and i dont understand what each parameter in the mysql_connect is, and i dont know what they do therefore im not sure what im supposed to enter in but everyone i keep reading about seems to be inputing random values? I could use a brief explanation on that, because i am stuck at connecting and cant even get past this point sadly enough. Also i have been reading that mysql_connect is deprecated and isnt valid anymore but i dont understand what im supposed to use as an alternative. I know its mysqli but thats it and im unclear of the syntax.
mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "start<br/>";
try {
$mysqli= new mysqli('localhost', 'myusername', 'mypassword', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
If you need to know how to create users, what the heck the hostname is, how to grant access (often useful after the connect :>), just ask.
Try this code in 'connect.php'
<?php
error_reporting(0);
$con=mysql_connect('localhost','root','');// here 'root' is your username and "" is password
if(!$con)
{
echo 'not connect';die;
}
mysql_select_db('dbname',$con);// here 'dbname' is your database name
?>
And also try following code to include sql connection in your other php file(main.php)
<?php
include 'connect.php';
$sql = "SELECT * FROM myUsers";
$result=mysql_query($sql);
?>
Let me convert it to mysqli for you and maybe that will fix the problem. Also, make sure the username, password, and database name are correct.
Try this code. At very least, it will provide a better error message for debugging.
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
$con = mysqli_connect($hostname, $username, $password, $databaseName) or die(mysqli_error($con));
?>
Main.php
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysqli_query($con,$sql);
?>
I have a php script I wrote and it will not return anything except "Hello".
<?php
echo "Hello";
$username = "me";
$password = "password";
$hostname = "localhost";
$dbname = "dbname";
//connection to the database
$dbhandle = new mysqli($hostname, $username, $password, $dbname)
or die("Unable to connect to MySQL");
echo "logged in";
// Sanitize variable
$user_id = intval($_GET['user_id']);
//update likes on specific id
$result = mysqli_query($dbhandle, "SELECT user_score FROM users WHERE id = '$user_id'")
or die("Unable to query");
// Send back the score
$return = array();
while ($row = mysqli_fetch_assoc($result)) {
$return[] = $row;
}
print json_encode($return);
//close the connection
mysqli_close($dbhandle);
?>
I had this script working before, then I moved it to another instance. I know I can login with my credentials to mysql and check that I have all privileges, and I know my username and password are correct. Is there something I need to change in my php? Or is there something I need to do so that when I access through a browser it shows like turn on the server?
I am not having anything returned except Hello, it does not even tell me "Unable to connect". This is very confusing to me. I should at least see "logged in" OR "Unable to connect" right?
Your are mixing the object oriented and procedural mysqli functions. When using the mysqli-constructor an object is returned even on failure, therefore the error is never shown.
Use this code instead to connect to your database:
$dbhandle = mysqli_connect($hostname, $username, $password, $dbname) or die("mysqli_connect failed");
Check the mysqli-documentation for further information.
You probably aren't getting any output because of your error_reporting settings in PHP. The first step would be to set display_errors = On in your php.ini, along with error_reporting = E_ALL. This will show all errors and you will get more information from your code snippet above. You can also set the error_reporting level in the PHP file itself by adding this line at the top of your file: error_reporting(-1);
More info on error_reporting here.
I have a registration script that doesn't work. It used to work but then suddenly it stopped working. I dont know what I've done or what happend. I have tried for like an hour now to find out where the problem is, but I can't seem to find it.
What happens? When I click register I don't get any errors but it doesn't upload to the database:
When I type: $res = mysql_query($query) or die ("ERROR"); it displays ERROR so I think it's related to that code:
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
$country = mysql_real_escape_string($_POST['country']);
$rights = '0';
$IP = $_SERVER['REMOTE_ADDR'];
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$query = mysql_query("SELECT username FROM users WHERE username = '".$username."'");
if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use.';
}
else{
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country',$rights,$IP,NOW())" ;
$res = mysql_query($query);
header("location:load.php");
}
}
I think you are getting the error because you are missing some quotes in your query for two columns wich really looks like not integers
'$email','$country',$rights,$IP,NOW())" //$rights and $ip doesn't have quotes
so your query would look like
"insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country','$rights','$IP',NOW())"
Use mysql_error() in order to see what the error message is. If you haven't changed anything in the script then it's either your database structure has changed or your rights have.
Update:
You don't have quotes around your IP value, which is surprising because you said that query worked until now. Anyway you should also consider saving IPs the RIGHT way. Good luck!