I am trying to exectute the following on the live server but it does not execute. On the local host everything is fine. I am able to execute other sql on the live server tho
$mysqli = new mysqli("localhost", "username", "password", "database");
if(isset($_POST['username'])&& isset($_POST['password']) ){
$username =$_POST['username'];
$password = md5($_POST['password']);
if ($mysqli) {
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("select acc.accountId, acc.firstname, prof.imagename from accounts acc inner join profilepicture prof on prof.accountId=acc.accountId where acc.emailAddress=(?) and acc.password=(?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
$stmt->bind_param("ss", $username,$password);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if(!empty($row)){
`enter code here`
`enter code here`// STATEMENTS TO EXECUTE IF DETAILS EXISTS
}
This could be the reason: You are logging into mysql with no default database, no username and no password
$mysqli = new mysqli("localhost", "", "", "");
should be something like this:
$mysqli = new mysqli("localhost", "user", "password", "database");
Read this http://php.net/manual/en/mysqli.quickstart.connections.php
In the live server or cpanel.. go to mysql section create the database and user and password... and give that user the permission to edit update and delete.. then in the
$mysqli = new mysqli("localhost", "", "", "");
add all the three the username password and database name..then.. it will work fine..
Hope it works
Related
I am new on this MySQLi connection. I have system codes here and working on WAMP server localhost. I changed the old mysql connection to new mysqli connection and got rid of these "deprecated errors". But But my problem is that I could not login or access query (sql related function). What I am saying is that I got rid of deprecated errors but could not login/access my database.
//This is my OLD connection:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("towertec_master") or die(mysql_error());
//This is my NEW connection
$link = mysqli_connect ("localhost", "root", "", "towertec_master") or die(mysql_error());
Also here is my OLD fetch connection:
$sql=mysql_query("SELECT organization_name,address,phone,email FROM system_config");
$row=mysql_fetch_assoc($sql);
$organization_name=stripslashes(trim($row['organization_name']));
$address=stripslashes(trim($row['address']));
$phone=stripslashes(trim($row['phone']));
$email=stripslashes(trim($row['email']));
NEW fetch connection:
$query = "SELECT organization_name, address, phone, email FROM system_config" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
As pointed out, your are still using the deprecated error function. Also, for your connection, you need to create the connection object which you do with "new".
$link = new mysqli_connect ("localhost", "root", "", "towertec_master");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
For your query, you are putting the error function in the wrong place.
$query = "SELECT organization_name, address, phone, email FROM system_config";
$result = mysqli_query($link, $query);
if (!$result) {
printf("Error: %s\n", mysqli_error($link));
}
Here's a MySQL pattern in PHP:
$username="username";
$password="password";
$database="username-databaseName";
// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = some query
$result = mysql_query($query);
I tried to replace most of it with a mysqli pattern and then stick the query part at the bottom like so:
//Database Information
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "username-databaseName"; //Name of Database
$db_user = "username"; //Name of database user
$db_pass = "password"; //Password for database user
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
GLOBAL $mysqli;
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// Search the rows in the markers table
$query = some query
$result = mysql_query($query);
However, I get this error message:
Invalid query: No database selected
What am I doing wrong?
First of all, you're calling mysql_query and not mysqli_query, like you intended to.
Second, since you're using the object oriented form, you need to call mysqli_query as a method:
$result = $mysqli->query($query);
I'm trying to output the results of a simple query using a Google Cloud SQL with a mysqli connection. I've properly set up a Cloud SQL instance and imported a SQL database. However, when I run my app, it seems to connect to the database - no errors are triggered there - but the logs show the following:
PHP Fatal error: Wrong SQL: SELECT * FROM students Error: No database selected in /base/data/home/apps/s~db-php-001/1.371796924944999585/main.php on line 18
Here's my code:
$conn = new mysqli(null,"root","",null,null,"/cloudsql/db-php-001:db-instance-001");
// check connection
if($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql='SELECT * FROM students';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
}
Obviously, I'm triggering that error, but I'm can't figure out why. There is definitely a table named students in the database.
Anyone have any ideas?
Thanks!! Joe
You've set your database name to null. A connection is made like so:
$mysqli = new mysqli("localhost", "user", "password", "database");
The mysqli constructor can take in the following parameters (in this order):
$mysqli = mysqli($hostname, $username, $password, $database, $port, $socket);
In your case, you've set the parameters to be:
$hostname = null; //Defaults to mysqli.default_host
$username = "root";
$password = "";
$database = null; //Defaults to ""
$port = null; //Defaults to mysqli.default_port
$socket = "/cloudsql/db-php-001:db-instance-001";
To clarify, you can pass null for the database name. In the query you'd need to use the fully qualified table name (<database>.Students in your case). Or you can use the mysqli_select_db() function to select the database to use.
I recently learned that mysql_* has been depreciated and i have a quick question on how to rewrite something.
$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);
I have tried rewriting it like this...
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
But when it posts my form i get the "Error connecting to MySQL database." error. I was able to fix it by just using this but i wanted to know how to add in the Error connecting.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
Any help would be great as i try to learn all of the new MySQLi stuff!
PHP website
Straight from php.net
<?php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
Edit:
The below will also allow you to do it your way.
$mysqli = mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
Then you can:
if (!$mysqli) {
//handle the error
}
Consider PDO if possible. They are kind similar to me.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
should be
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
if($mysqli->connect_error) die("Error connecting to MySQL database.");
the parameters for mysqli() are:
[ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]]
Not sure why you were trying to use the $db variable to set the port for the connection and then checking if the port variable is true...
For future reference the best place to look first, would be the docs
EDIT
As #Touch pointed out, you must check if error exists and not just that object exists. Edited code to reflect this.
Using mysqli:
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_database_name');
define('DB_USER', 'some_user');
define('DB_PASS', 'some_password');
$Connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$Connection->connect_errno)
{
//do your prepared stuffs
}
else
{
die("Database Connection error:".$Connection->connect_error);
}
or using PDO
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//do your prepared stuffs
$PDOConnection = null;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
}
I wrote a class called better_mysqli that extends mysqli making it easier to use.
The following example shows the answer to your question and also shows basic usage of the better_mysqli class. You can view a detailed example with lots of comments here: detailed usage of better_mysqli
<?php
include_once('better_mysqli.php'); // can be obtained from: http://pastebin.com/ATyzLUfK
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THE ONLY DIFFERENCE IN THE CONNECTION WHEN USING better_mysqli AND mysqli
// is $mysqli = new better_mysqli(...) and $mysqli = new mysqli(...)
// == Instantiate the mysqli database object (aka open the database) ==
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
// == select example ==
unless( $sth = $mysqli->select('select * from table1 where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'), $debug_level=0, $verbose_debug_output)){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
while($sth->fetch()){
echo $row['col1'] .', '. $row['col2'] .', and '. $row['col_etc'] .' are accessed like that.<br>';
}
// == insert example ==
$statement = "insert into table1 (col1, col2, date_col, col_etc) values (?, ?, NOW(), ?)";
unless( $mysqli->insert($statement, array('col1_insert_value', 'col2_insert_value', 'col_etc_value'), $debug_level=0, $verbose_debug_output, $id_of_new_record) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == update example ==
unless($mysqli->update("update table1 set col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == delete example ==
unless( $mysqli->delete("delete from table1 where col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// in all cases statements are prepared just once and cached so if you reuse any statement the already prepared statement handle is automatically used
?>
When executing the
mysqli_bind_result();
I receive an error saying "Call to undefined function".
My code looks as follows:
$mysqli = new mysqli("localhost", "root", "", "*****");
if(isset($_POST['login'])){
if($_POST['username']){
if($_POST['password']){
$username = $_POST['username'];
$passwordtmp = $_POST['password'];
$password = md5(md5($passwordtmp));
//Connect to Database//
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Check if user exist in database//
$query = mysqli_query($mysqli,"SELECT * FROM users WHERE username = '$username'");
$numrows = mysqli_num_rows($query);
if($numrows == 1){
if($stmt = mysqli_prepare($mysqli, "SELECT password FROM users WHERE username = '$username'")){
mysqli_execute($stmt);
mysqli_bind_result($stmt,$passw);
while(mysqli_stmt_fetch($stmt)){
$pass = $passw;
}
Additional Information:
I transfered this code from a different computer to my laptop using the same connection to my mysql database.
$mysqli = new mysqli("localhost", "root", "", "*****");
I copied the exact database to my laptop and both my computer and laptop are using wamp.
I am wondering if this could be a connection to the database issue, or just a coding error. But it works perfectly on my original computer without any problems.
Thank you in advance. I will give credit for helpful answers.
You're probably using PHP > 5.4, as the function mysqli_bind_result was removed in PHP 5.4.
Change it to mysqli_stmt_bind_result and that should fix your problem.
mysqli_stmt_bind_result($stmt, $passw);