This question already has answers here:
How do I get PHP errors to display?
(27 answers)
Closed 5 years ago.
<?php
//Get Value
$username = $_POST['user'];
$password = $_POST['pass'];
//Connet To The Server And Select Database
mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
mysqli_select_db("xxxxx");
//Query The Database For User
$result = mysqli_query("select * from user where username = '$username' and password = '$password'")
or die("Failed to query database ".mysqli_connect_error());
$row = mysqli_fetch_array($result);
if (empty($username)) {
header('Location: fa.html');
} elseif (empty($password)) {
header('Location: fa.html');
} elseif ($row['username'] == $username && $row['password'] == $password){
header('Location: su.html');
} else{
header('Location: fa.html');
}
?>
I have no experience to code PHP so i have no idea what's wrong is my code.
I have replace "mysql" into "mysqli" but it is still not working correctly.
It's work fine when running "mysql_*" and using my local Window web server.
But when i put it into Linux server it occur error message "Failed to query database ".
Add the fourth parameter here as database name like
mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx", "database_name");
and remove
mysqli_select_db("xxxxx");
A sample way of writing php code would be
$link = mysqli_connect("server_name","username","password","database_name");
if(mysqli_connect_error()) {
die("There was an error connecting to the database");
}
$query = 'yourQuery';
$result=mysqli_query($link,$query);
if ( false==$result ) {
printf("error: %s\n", mysqli_error($link));
}
This will work
Hope it helps
You need to trap for more errors to see where it's failing. Right now all you know is that it's failing at-least by the mysqli_query() line where you do trap for errors.
First you have to ensure that you can actually connect to the database server.
Change:
mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
to
if(!mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxx"))
{
die("Could not connect");
}
then you should also trap for errors on selecting the database. Change:
mysqli_select_db("xxxxx");
to
if(!mysqli_select_db("xxxx"))
{
die("Could not select database");
}
Edit: Also you really didn't need to blank-out your IP. 192.168.1.* is a class C private address - meaning it is not accessible from outside your local network.
You need to learn more, because these are really just the basics. The reason why your code works locally and doesn't on the remote server is probably caused by your DB access - it obviously isn't the same. You need to change your credentials and your db IP to match your remote server if you want to deploy your code there.
Related
This question already has answers here:
How can i solve this "Warning: mysqli_connect(): (HY000/1049): Unknown database" problem?
(6 answers)
Database exists but returns an error saying "Unknown Database"
(1 answer)
Closed 2 years ago.
I was trying to create a login using PHP and MySQL for the database, I did everything but when I try to run the site it gives me a connection error with the database even though I created the database and gave it the corresponding name (login)
This is the code
db_connect.php
<?php
$connection = mysqli_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'login');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
authen_login.php
<?php
require('db_connect.php');
if (isset($_POST['user_id']) and isset($_POST['user_pass'])){
// Assigning POST values to variables.
$username = $_POST['user_id'];
$password = $_POST['user_pass'];
// CHECK FOR THE RECORD FROM TABLE
$query = "SELECT * FROM `user_login` WHERE username='$username' and Password='$password'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
//echo "Login Credentials verified";
echo "<script type='text/javascript'>alert('Login Credentials verified')</script>";
}else{
echo "<script type='text/javascript'>alert('Invalid Login Credentials')</script>";
//echo "Invalid Login Credentials";
}
}
?>
And the error is this
Database Selection Failed Unknown database 'login'
(I add to the question a photo of the database that maybe the error is there)
You dont have a database called shoolbrk, your database appears to be called login.
Also you you should use mysqli_connect_error() to see connection errors and not mysqli_error($connection). Thats for all other errors other than connection errors.
You can also simplify the connection script as follows
<?php
$connection = mysqli_connect('localhost', 'root', '', 'login');
// database name ^^^^^
if (!$connection){
echo $connection ->connect_error;
}
A better solution would also be to not die() or show errors to the world, instead add mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); to the connection script.
Port number issue
See this answer https://stackoverflow.com/a/62831626/2310830 which describes how WAMPServer manages MySQL and mariaDB port number usage. And how it will allow you to switch the default to MySQL so it uses port 3306 which will allow you to write your code in a way that will run anywhere without having to change the port number. As most hosting companies will have either MySQL or mariaDB listening on 3306
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I'm currently trying to create a php file that can verfify a user's input on user and pass against a sql database and bring back a response to the user...via website. But I keep getting this error:
Parse error: syntax error, unexpected '$row' (T_VARIABLE) in /srv/disk7/1855095/www/hmfs.dx.am/index.php on line 24
<?php
define('DB_HOST', 'localhost');
define('DB_HOST', 'practice');
define('DB_HOST', 'root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn()
{
session_start(); //starting the session for user profile page
if(!empty($_POST['user']))
//checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM UserName
where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query)
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] $row['pass'];
echo "SUCESSFULLY OGIN TO USER PROFILE PAGE...";
}
else
}
echo "SORRY...YOU ENTERED THE WRONG ID AND PASSWORD...PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Any help? :(
your error message says to look at line 24, in which you find this:
$_SESSION['userName'] $row['pass'];
which isn't a valid statement. It should probably be
$_SESSION['userName'] = $row['pass'];
although I would not store a password in a session (session data might be stored in a shared temporary directory).
Please also note that your code is extremely vulnerable to SQL injection. Read up on prepared statements, and don't use mysql_ which is deprecated since 2013. Use mysqli_ or PDO instead.
Additionally, for real-world code, you should hash your passwords when storing them.
Here are some tips
1)Don't use mysql. It's deprecated and very vulnerable. Use Mysqli or PDO instead.
2)Never check a password in the query itself. Because in your code if I enter your username and ' OR 1=1 as my password I will login in your account. Select by username then check the password via PHP
3) your error is because of a missing ; at the end of $row = mysql_fetch_array($query) or because of a missing = between $_SESSION['userName'] and $row['pass'];
Change
$_SESSION['userName'] $row['pass'];
To
$_SESSION['userName'] = $row['pass'];
It quite simple
you've forgotten to use semicolon after $_SESSION['userName']
Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This is probably just a stupid mistake somewhere but i cant connect to mysql.
And it have been bugging me for days now!
Im trying to create a database for a web shop tutorial am doing.
And this is done thru Dreamweaver and cPanel.
Im trying to connect to my mysql database from this code:
-----connect_my_sql.php-----
<?php
$db_host = "hostip";
$db_username = "build";
$db_pass = "*****";
$db_name = "myonlinestore";
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass", "$db_name") or die ("could not connect to mysql".mysql_error());
?>
(password and hostip is changed)
Where username is connected to the database and psw is the right one.
And i dont get any error from .mysql_error()
all this is done in a subfolder on my main domain on godaddy.
Have tryed to do a admin page and i cannot connect to my database to use the log in i have created in mysql.
witch is the following code:
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
(i removed all the styling in the code)
and all i get is that the information is incorrect, but i have created a admin table and user in my database.
But i cant log on.
All i get from this is that there is some issue when im trying to connect.
and it has to be from my end becouse godaddy cant see any errors or that i cant connect on there logs.
I will be very greatfull if you could help me with this problem.
Thanks
You can't connect to database because you opened connection with mysqli api and after you use mysql_query that actually belongs to mysql api and doesn't have any connection to database
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
//^ here you use the wrong api
Just change this with mysqli query command, learn more here
The top file is called 'connect_my_sql.php'
file being included is 'connect_to_mysql.php";
Also, use 'require_once' since the file is required for the script to function.
Additionally to what the answers of #DoctorDerp and #Fabio, this is wrong too
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass", "$db_name") or die ("could not connect to mysql".mysql_error());
remove everything after the or, and then on the line under add an if to test connection like so the code become like this
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass", "$db_name");
if(!$myConnection){
die("Cannot connect to database");
}
i use a simpler sign-in script i created.
$dbc=mysqli_connect("host","username","password","database") or die ("Error in Connecting to database");
$email=$_POST["idamuid"];
$password=$_POST['idamupassword'];
$email=htmlspecialchars(mysql_escape_string($email));
$password=htmlspecialchars(mysql_escape_string($password));
$query="select member_email from members where member_email='$email'
and member_password=sha('$password') ";
$result=mysqli_query($dbc,$query);
if(mysqli_num_rows($result)==1){
session_start();
$_SESSION['userid']=$email;
header("location:index.php");
mysqli_close($dbc);
}
else{
echo "Login Unsuccessful";
echo '<p>Please Try Again</p>';
I have a "Windows Apache MySQL PHP" server on my laptop. I get absolutely no error messages, but when I send things to MySQL via PHP script, nothing happens in MySQL (I also sent something via the MySQL command prompt and it looks like it just made a test table and didn't put anything in it like I asked, but I'm not positive I did everything I should have in this case). I've rescripted my whole page a different way and it still doesn't work.
Here is a picture of my form and how the table looks in MySQL:
System:
Windows 7 Home Premium SP1 64 bit--
Apache 2.4.4 32 bit with ssl0.9.8--
PHP 5.4.11 32 bit VC9--
MySQL 5.5.31 64 bit with Navicat Lite
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'projectedin');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " .mysql_error());
function NewUser()
{
$userName = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$password = $_POST['password'];
$birthday = $_POST['birthday'];
$gender = $_POST['gender'];
$query = "INSERT INTO users (username,firstname,lastname,password,birthday,gender) VALUES ('$username','$firstname','$lastname','$password','$birthday','$gender')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-Up.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
newuser();
}
else
{
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
mysqli_close ($con);
?>
There are a number of concerns here (more on that later), but this might be an issue for you:
You try to call your new user function like this:
newuser();
However it is named NewUser. This is case sensitive and will not work. Look at your error logs to see the errrs you are getting here.
Other issues:
You are using deprecated mysql_* functions. If you are learning PHP, learn the right way and use mysqli or PDO.
You are not escaping your input at all, and are therefore very prone to SQL injection attacks.
You are kind of randomly using functions when they don't really bring you any value.
You are kind of going outside of typical PHP coding standard when having your function names start with uppercase letter. This is a bit unusual for PHP, though this would actually work.
You have an error in your Signup query:
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST['username']' AND password = '$_POST['password']'") or die(mysql_error());
I changed $_POST[username] to $_POST['username'] and $_POST[password] to $_POST['password']
Also, you are vulnerable for MySQL injections, you should use mysql_real_scape_string function to clean each $_POST var: $userName = mysql_real_scape_string($_POST['username']);
Finally, you should not use mysql* functions, they are deprecated.