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.
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);
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.
I just set up the prepared query selection but it seems like it does not work.. It shows blank page instead of the content it should show..where is problem?
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $mysqli->prepare('SELECT configured FROM members WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
if($row['configured'] == ""){
if (isset($_SESSION['user_id'])) {
?>
With this code I want to check if user has configured his settings and so if yes, then if he is logged in. But the page shows nothing even though I have there everything correct after that code I posted...
You're using $conn to connect with, then $mysqli in your prepare statement.
This
$stmt = $mysqli->prepare
Which should read as
$stmt = $conn->prepare
Also make sure you've started the session.
http://php.net/manual/en/function.session-start.php
Check for errors:
http://php.net/manual/en/function.error-reporting.php
and you have 3 missing closing braces in your posted code.
I see you're using $username = ""; in your DB connection and then using the same variable to bind with.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I feel like a total n00b for not understanding what I'm doing wrong, but here goes.
I'm writing a simple web form that's storing information in a MySQL database. I'm getting this error:
mysqli_stmt_init() expects parameter 1 to be mysqli, null given in /myfile.php
Here's my code:
$server = 'localhost';
$username = 'myusername';
$password = 'mypassword';
$db = 'mydb';
$link = mysqli_connect($server, $username, $password, $db);
.
.
.
$stmt = mysqli_stmt_init($link); /*This line throws the error*/
Any ideas? Thanks in advance.
Are you 100% sure you are successfully connecting to the database?
Add at the top of your script:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Also add right below your connection line:
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
If this is your dev server you should probably set the following lines in your php.ini file rather than in each script.
error_reporting = E_ALL
display_errors = on
if that doesn't solve you problem than you should print our $link to see what it is.
I'm new to PHP and have installed on Linux to boot (also a newbie).
Anyway, PHP is working...
<?
$myVar = "test";
echo($myVar);
?>
... works just fine.
But...
<?
$dbhost = "localhost";
$dbuser = "myuser";
$dbpass = "mypass";
$dbname = "mydb";
echo($dbhost . "-" . $dbuser . "-" . $dbpass . "-" . $dbname);
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");
print $conn;
mysql_close($conn);
phpInfo();
?>
... does nothing. Nor errors, nothing. Its as if the code isn't even there.
Any help?
Try to do the following:
First make sure display_errors is turned on in your php configuration file. Also set the level of error_reporting to show all errors, including strict (error_reporting = E_ALL|E_STRICT). After you make changes, restart your webserver.
Run phpinfo(), and check that the mysql extension is installed and working. If it isn't make sure that you uncommented it in the php configuration file (again, remember to restart apache after each change to the configuration file).
At this point MySQL should be loaded and working, and you should be able to tell from the error (if it persists) what's the problem.
Try also dumping the contents of the connection result ($conn) to see what it contains.
In general, I'd recommend using long php tags (<?php and not <?) since it is more portable (short tags are off by default in PHP 5 installations).
Try adding this to the top of your code:
error_reporting(E_ALL);
If it does nothing, doesn't that mean that it connected fine? What output do you expect out of that statement?
You could try
error_reporting(E_ALL);
$conn = mysql_connect("localhost", "myusername", "mypassword");
if(!$conn) {
echo 'Unable to connect';
} else {
echo 'Connected to database';
}
var_dump($conn);
edit: Addressing the comment saying that you have a mysql query setup, if you are not seeing "success" it means something is wrong with your query. Add to the above
$sth = mysql_query("SELECT * FROM tablename");
if(!$sth) {
echo 'unable to query: ' . mysql_error();
} else {
echo 'success';
}
Is there more code than you're showing us? The block you have just sets up a connection. You won't see anything at all if it succeeds, you have to use $conn to do something.
To confirm, try changing your password to a deliberately wrong value, and then see if you get an error. If you do, the code works just fine.
Connecting to a database with
$conn = mysql_connect("localhost", "myusername", "mypassword") or die("Unable to connect");
will have no (visible( results if the connection was made succesfully. However, once you run this statement, you can use the other mysql functions to make make queries to the database.
Connecting to a database tells your program "hey, I want to talk to this database".
This code is supposed to create a db connection, nothing else. What do you expect to see?
Try this
<?php
$conn = mysql_connect("localhost", "myusername", "mypassword")
or die("Unable to connect");
print("code sample");
print $conn;
?>
It should print you something like "resource #1"...
And then you may use that connection to communicate with db server