So I'm not sure as to why PHP is not creating a database. Let me show what my code looks like first, and then I will quote what warning/error it's giving me:
<?php
// Connection
$con = mysqli_connect("localhost", "root", "1monica1");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Creating a database
// The database is called alarm_db
$sql = "CREATE DATABASE alarm_db";
if (mysql_query($sql, $con))
{
echo "Database alarm_db created sucessfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
The error and warning I keep getting is this:
Warning: mysql_query(): A link to the server could not be established in B:\DropBox\Dropbox\EbadlyAgha\Ebad\reminders.php on line 51
Error creating database:
Line 51 is where the if (mysql_query($sql, $con)) is. Also, it won't give me the mysqli_error($con). It is just blank.
My MySQL connection is fine, because I never see the "Failed to connect to MySQL" statement.
It should be in mysqli_* while you executing DB creating query.
if (mysqli_query($sql,$con)) {
echo "Database alarm_db created sucessfully";
}
Try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.
Your connection is being generated by the mysqli library:
$con = mysqli_connect
but you are trying to query it using the mysql library:
mysql_query($sql,$con)
You need to be consistent about which library you use. Stick to mysqli throughout (since mysql is deprecated).
Note that mysqli_query expects the connection before the SQL:
mysqli_query($con, $sql);
You can try this to create a database using PHP:
<?php
$con = mysql_connect('localhost', 'root', '');
$query = mysql_query('create database alarm_db') or die(mysql_error());
if($query)
{
echo 'Database is created';
}
else
{
echo 'Database is not created';
}
?>
Related
i want to move my sql database and i have exported and imported mysql.sql file from localhost to live server and now i m not getting the files and content from that database. what i do ? i did make sure connection to database if fine and successful
here's my page http://shooop23.byethost7.com
<?php
$db = mysqli_connect('','','','');
if(mysqli_connect_errno()){
echo'Database Connection Failed with following errors: '. mysqli_connect_errno();
die();
}
?>
Once you have successfully established a connection to MySQL, you need to perform a query specifying what you want to retrieve and then subsequently retrieve it.
The following example uses mysqli_fetch_row
You should explore the documentation to learn the basics.
$db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if(mysqli_connect_errno()){
echo'Database connection failed with the following error: '.mysqli_connect_errno();
exit;
}
if ($result = mysqli_query($db, "SELECT MyCol1,MyCol2 FROM MyTable")) {
while ($row = mysqli_fetch_row($result)) {
echo"{$row[0]} - {$row[1]}<br>");
}
mysqli_free_result($result);
}
mysqli_close($db);
$db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
$sql="SELECT * FROM login";
here i connected and stored my database and set a sql command (which is now a string) into these two veriables.
if(mysqli_connect_errno()){
echo'Database connection failed with the following error: '.mysqli_connect_errno();
exit;
}
this is to check if the database is correctly connected, if not then it will show some errors.
$result = mysqli_query($db,$sql);
here i put the database and the sql command to run my query.
while($row = mysqli_fetch_array($result)){
echo $row['username'];
}
here finally outputting the usernames(username is one of the column in my table in this case) which matched with that query
i will suggest This Sql site to get a better understanding on sql queries and try to improve the secuirty because this is the basic point where hackers try to inject their attact most offenly.
Note : If your table's in the database are empty then it will not able to fetch anything
I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.
This is a somewhat simple task, I am trying to compare a username to that in the database. I am testing it out in a single php file before I do it properly. My code is below. Basically I have a user, which is in the database and I am checking if it is in there.
<?php
$db_connect = mysql_connect("127.0.0.1", "root", "anwesha01", "mis");
//Check if connection worked.
if(!$db_connect)
{
die("Unable to connect to database: " . mysql_error());
}
//For testing purposes only.
else
{
echo "Database connect success!";
}
$user = "alj001";
$query = "SELECT Username FROM `user` WHERE `Username` = '".$user."'";
//What is being passed through the database.
echo "<p><b>This is what is being queried:</b> " . $query;
//Result
if (mysql_query($query, $db_connect))
{
echo "<br> Query worked!";
}
else
{
echo "<p><b>MySQL error: </b><br>". mysql_error();
}
?>
The result I get is:
Database connect success!
This is what is being queried: SELECT Username FROM user WHERE Username = 'alj001'
MySQL error: No database selected
First I had my mysql_query without the $db_connect as it is above, but I put it in and I still get "no database selected".
Ive looked at the w3c schools for the mysql_query function, I believe I have done everything correctly. http://www.w3schools.com/php/func_mysql_query.asp
Because you haven't called mysql_select_db. Note that the 4th parameter to mysql_connect is not what you think it is.
That said, you really should be using PDO or mysqli, not the plain mysql_ functions, since they're deprecated.
I tried it connection to database connection to database is successful but when i try to match user information with database it gives me a error NO database is selected
i tried it connecting to database using different method but nothing worked
<?php
//CREATING CONNECTION TO DATABASE
$con= new mysqli("localhost", "****", "***", "*****");
$con->select_db("lel_server_user_db_secured");
if(mysqli_connect_errno())
{
echo "Problem With connection to database Please contact administrator regarding this error";
}
/* RETURNS NAME OF DEFAULT DATABASE
if ($result = $con->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
*/
/*
$host="localhost";
$db_user="sky.xpert";
$db_pass="havefun344";
$database="lel_server_user_db_secured";
mysqli_connect($host,$db_user,$db_pass,$database) or die ("Failed to connect");
mysqli_select_db($database) ;
*/
session_start();
//GATHERING DATA FROM USER FORM
$email=$_POST["login"];
$pass=$_POST["pwd"];
//COMMANDING WHERE TO FIND MATCH FOR LGOIN INFORMATION
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
//IF MATCH FOUND THEN SETTING SESSION AND REDIRECTING IT TO LOGGED PAGE
if($match==1)
{
$_SESSION['loggedin'] = "true";
header ("Location: logged.php"); //REDIRECTING USER TO ITS HOMEPAGE
}
else //IF MATCH NOT FOUND THEN REDIRECTING IT BACK TO LOGIN PAGE
{
$_SESSION['loggedin'] = "false";
header ("Location: index.php");
}
//PERSONAL COMMENTS OR DETIALED COMMENTS
//PROBLEM WITH THIS SCRIPT GIVING OUTPUT ON LOGIN "NO DATABASE SELECTED"
//REFRENCE from http://www.dreamincode.net/forums/topic/52783-basic-login-script-with-php/
?>
You are initializing a connection to your database with mysqli. Then you try to do queries with mysql. Obviously, there is no connection with the database made through that library, and therefore it fails with an error. Change mysql_query to mysqli_query.
General note
Your current code is vulnerable to sql injection attacks, because you do not sanitize the input from the user before putting it in a query. Consider using prepared queries.
The database lel_server_user_db_secured may be not exist.
Content to your mysql:
mysql -hlocalhost -uusername -p
then input your password. After login, type command:
show databases;
check if lel_server_user_db_secured is in the result.
update1*
change the code below:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
to:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$result = mysqli_query($con, $veryfy) or die ( mysqli_connect_errno() );
$match=0;
$match=mysqli_num_rows($result);
var_dump($match);
In the first half of your program you have used mysqli and in the latter half mysql. Either use mysqli or mysql. I would recommend using mysqli in your entire program so that you are not vulnerable to SQL injection
you can simply do it by
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
there is no need to do $con->select_db("lel_server_user_db_secured"); again
and using mysqli isnt mean your code is safe ... your code is still vulnerable to SQL injection Use prepared statement instead or atleast mysqli_real_escape_string
You need to escape all request properly
and its possible that your database isnt exist so check that its exist first
AND you are mixing tow different API
you can not use MySQLi functions with MySQL_* function
i am new in php and want to know the code for php mysql database connection code
Refer to the PHP documentation for mysql_connect.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Here is the bare bone of it:
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);
$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);
mysql_query(... , $db2);
More Info:
http://php.net/manual/en/function.mysql-connect.php
MySQL PHP Connect Tutorial
A Detailed Tutorial:
http://www.phpf1.com/tutorial/php-mysql-tutorial.html?page=1
<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("test") or die(mysql_error());
echo "Database was selected!<br/>";
?>
Watch also mysqli,it's the "new way" of connecting to mysql
http://php.net/manual/en/book.mysqli.php
it has more functions and there are rumors that in php6 mysql will be deprecated for the mysqli implementation.
you can use it as an object(but if you're new also to OO it may be a little more difficult to understand)like this:
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');//you can also use $db=new mysqli(....) but mysql_connect does the same thing and it's more cler on what it's doing
//--a simple query--
if($result=$db::query('SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',$result->num_rows,'rows<br/>';
while($row=$result->fetch_assoc()){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
$result->close();
}
else//query error
die('MYSQL ERROR:'.$db->error);
or with functions like in mysql
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');
//--a simple query--
if($result=mysql_query($db,'SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',mysql_num_rows($result),'rows<br/>';
while($row=mysqli_fetch_assoc($result)){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
mysql_free_result($result);
}
else//query error
die('MYSQL ERROR:'.mysqli_connect_error());
You can also use a persistent mysql connection prepending 'p:' to the sql host,for example if your host is sql.myhost.com:
$db=mysqli_connect('p:sql.mysqlhost.com','database_username','password','database_name');
Using a persistent connection should give you a great performance boost and mysqli should handle the persistent connection a lot better than the normal mysql extension.
Remember to sanitize the input of your query to avoid SQL INJECTION,you can do like this:
$result=mysql_query($db,"SELECT name,value FROM mytable where name='".mysqli_real_escape_string($input_name)."'");
or using a prepared statement that's a little more complicated and it's better only if you repeat the same command multiple times only changing the input data.