Error occurred ... no database selected - php

I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.

You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}

I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.

Related

Cant connect php to mysql

New to php and am connecting form attributes to php to connect to a godaddy mysql. Every attempt ends in a blank screen with no error messages. Is there any syntax errors the jump out? My sublime text wont register php syntax, but thats another problem for another time. I may need to call up godaddy support? the password has been removed for privacy.
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysql_select_db('EOTDSurvey', $con)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
$_POST['BI1']
$_POST['BI2']
$_POST['BI3']
$_POST['BI4']
$_POST['BI5']
$_POST['BI6']
$_POST['BI7']
$_POST['BI8']
$_POST['BI9']
$_POST['BI10']
$_POST['BI11']
$_POST['BI12']
$_POST['BI13']
$_POST['BI14']
$_POST['BI15']
$sql = "INSERT INTO Survey1(BI1)"
$sql = "INSERT INTO Survey1(BI2)"
$sql = "INSERT INTO Survey1(BI3)"
$sql = "INSERT INTO Survey1(BI4)"
$sql = "INSERT INTO Survey1(BI5)"
$sql = "INSERT INTO Survey1(BI6)"
$sql = "INSERT INTO Survey1(BI7)"
$sql = "INSERT INTO Survey1(BI8)"
$sql = "INSERT INTO Survey1(BI9)"
$sql = "INSERT INTO Survey1(BI10)"
$sql = "INSERT INTO Survey1(BI11)"
$sql = "INSERT INTO Survey1(BI12)"
$sql = "INSERT INTO Survey1(BI13)"
$sql = "INSERT INTO Survey1(BI14)"
$sql = "INSERT INTO Survey1(BI15)"
if ($conn->query<$sql) === TRUE) {
echo "IT FUCKING WORKS.";
}
else{
echo "didnt workkkkkk";
}
$conn->close();
?>
please connect database like this...
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
And Use mysqli_select_db instead of mysql_select_db
And insert semi-colon (;) after every line end according to php code standard.
There are a lot of issues with this code, as mentioned the mysqli_select_db issue. The $_POST['BIx'] will also cause errors because there is no semi-colon after each statement. You're missing a '(' on the line if ($conn->query<$sql) === TRUE) { not to mention that line will not work anyway because you're logically comparing a resource type (I think) to a string.
You're also never executing the insert statements. All around I seriously think you should practice PHP coding some more and read up on how to use mysqli properly: see here.
Regards
EDIT: You also have a closing PHP tag at the end of your script which is generally not a good idea as explained here
EDIT 2: Also using an IDE such as Netbeans is always a good idea as it can highlight syntax errors instead of asking SO to do it for you ;)
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysqli_select_db('EOTDSurvey', $con);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
############# Function For Insert ##############
function insert($tableName='',$data=array())
{
$query = "INSERT INTO `$tableName` SET";
$subQuery = '';
foreach ($data as $columnName => $colValue) {
$subQuery .= " `$columnName`='$colValue',";
}
$subQuery = rtrim($subQuery,', ');
$query .= $subQuery;
pr($query);
mysqli_query($con,$query) or die(mysqli_error());
return mysqli_insert_id();
}//end insert
#########################################
if(isset($_POST['submit'])){
unset($_POST['submit']);
//print_r($_POST);
$result=insert('Survey1',$_POST);
if($result){
echo '<script>window.alert("Success!");</script>';
echo "<script>window.location.href = 'yourpage.php'</script>";
}
}
$conn->close();
?>

Switch from mysql_connect to PDO: mysql_num_rows() expects parameter 1 to be resource

I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';

connect to sql database with php

Im trying to connect to sql database with PHP.For some reason when i run the code i am getting below error.
Parse error: syntax error, unexpected '$result' (T_VARIABLE) in C:\xampp2\htdocs
\tutorials\abb.php on line 13
My Code is this...
$user = 'root' ;
$pass = 'xcvsdffd' ;
$db = 'testdb' ;
$con = new mysqli('localhost', $user , $pass , $db) or die("UNABLE TO CONNECT");
$selected = mysql_select_db($db,con)
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name33'}."
".$row{'year'}."<br>";
}
//close the connection and recordset objects freeing up resources
$result->Close();
$con->Close();
$result = null;
$con = null;
?>
There are two reasons which was the reason for your errors..
1.
You missed a semicolon ; and a $ sign. Below is valid one.
$selected = mysql_select_db($db,$con); //Replace this with your existing line.
2.
You are mixing mysql_* and mysqli_*
Sidenote:
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
The PDO way...
<?php
$dsn = 'mysql:dbname=testdb;host=localhost';
$user = 'root';
$password = 'xcvsdffd';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
For more information.. read the PHP Manual. or use PreparedStatements in MySQLi
Mysqli works with MySQL version 4.1.13 or newer; if your version is old then u should connect your db the old way like this:
$con=mysql_connect("localhost","root","pass");
mysql_select_db("database_name",$con);
They always tell me that MySQL command is now depreciated or something. That's why it's a good practice to use PDO or MySQLI. It's easy to use, if you'll appreciate it's use.
Now going to your code:
$connection = new mysqli("localhost","user","password","database name");
$selectDatabase = mysqli_select_db($connection,"database name");
$connection->query ("SELECT * FROM test");
Hope this helps
Try this below , if you are creating mysqli connection then you dont have to use mysql_select_db($db,con) for again select database. or use semicolon after this line
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Reference
there might be a semicolon missing in a line .
mysql_select_db($db,$con);
Try this
<?php
$username = 'root';
$pass = 'pass';
$db = 'db';
$link = mysqli_connect('localhost',$username,$pass,$db);
if(!link){
echo "Not Connected to DB" . mysqli_connect_error();
$result = mysqli_query($link, "SELECT * FROM test");
while($row = mysqli_fetch_array($result)){
echo "ID: " . $row['id'];
echo "Name: " . $row['name33'];
echo "Year: " . $row['year'];
}
?>
Querying in PHP must be consistent, meaning if you use mysqli you should use it throughout the PHP file, and if you use mysqli you must also use it throughout the PHP file. mysqli and mysql also has different code constructions. So search on the web for their proper construction. Hope this helps

Mysqli num row returned is not working

I'm wondering why it is not working for mysqli eventhou mysql_num_row is working.
if (mysql_num_rows($rows) > 0) {
echo "<p>That name has been taken </p>";
}
That is mysql. But, Im trying convert it to mysqli.
if (mysqli_num_rows($rows) > 0) {
echo "<p>That name has been taken </p>";
}
It supposed to be displayed on the screen but it's not. And there is nothing error message displayed. Or am I missing something? Any ideas?
First, a quick tutorial on some of the differences between mysql_* and mysqli_* functions.
In mysql_* you would have 3 parameters for your DB connection, then have a seperate line for your DB selection.
For example:
$db = mysql_connect("host","username", "password");
$db_selected = mysql_select_db('db_name', $db);
if (!$db_selected) {
die ('Can\'t use this : ' . mysql_error());
}
Your query would come first, followed by your DB connection.
For example:
mysql_query($query,$db);
But in mysqli_* things have changed including the parameters location. You now put all 4 parameters, for example (if you haven't done so yet):
$db = new mysqli("host","username", "password", "db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
then the DB connection would come first, followed by the query instead of the other way around:
mysqli_query($db,$query);
A sample query:
$email = mysqli_real_escape_string($db,$_POST['email']);
$query = mysqli_query($db, "SELECT * FROM table_name WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
$sql="INSERT INTO table_name (email) VALUES ('$email')";
if (!mysqli_query($db,$sql))
{
die('Error: ' . mysqli_error($db));
}
}
You could try this code:
$connect = new mysqli("localhost", "user", "password", "database");
$query = "SELECT name FROM table";
$statement= mysqli_prepare($connect, $query)
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
if (mysqli_stmt_num_rows($statement) > 0) {
echo "<p>That name has been taken </p>";
}
mysqli_stmt_close($statement);
mysqli_close($connect);

checking if a database exists

The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.
function cpanel_db_connect($dbname) {
// normalize
$dbname = convert_to_slug($dbname);
$dbname = CPANEL_USER . '_' . $dbname;
$dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;
// connnect database
$mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
if ($mysqli->connect_error) {
return false;
}
return $mysqli;
}
It's not a good practice to suppress warnings/errors using the # sign in PHP. You could accidentally suppress an invalid username or password message and you would never know it.
A more appropriate way of checking if the database exists is creating a new instance of Mysql or Mysqli (without specifying the default database) and executing the following query (similar to Marc B's comment):
SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME='my_database_name'
Then you can check the value of the key exists to see if the database is there or not.
Here's a sample code:
// statement to execute
$sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="my_database_name"';
// execute the statement
$query = $mysqli->query($sql);
// extract the value
$row = $query->fetch_object();
$dbExists = (bool) $row->exists;
It is a bit longer but it's safer.
$mysqli = #new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
The above works!
This works, just replace $dbname in this code:
if (empty (mysql_fetch_array(mysql_query("SHOW DATABASES LIKE '$dbname' ")))){
echo "DB does Not exist"; }else{ echo "DB exists!";}
Updating to MYSQLI:
$conn = new mysqli('localhost', 'root', '');
$dbname='test';
if (empty (mysqli_fetch_array(mysqli_query($conn,"SHOW DATABASES LIKE '$dbname'"))))
{
echo "DB not exist<br>";
}
else
{
echo "DB exist<br>";
}
Here's how to connect to DB server without selecting a DB, and only connecting if DB exists:
$mysqli = new mysqli($db_biz['server'], $db_biz['user'], $db_biz['password']);
$query = 'SHOW DATABASES LIKE "' . $db_biz['dbName'] . '"';
$resShowBizDB = $mysqli->query($query);
if ($resShowBizDB->num_rows == 1) { //Found database
$mysqli->select_db($db_biz['dbName']);
if ($mysqli->connect_errno) { //Check for errors
var_dump($mysqli);
echo "Failed to connect to biz database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset('utf8');
} else { //Didn't find DB
die('<h1>ERROR</h1><p>Found no database</p>');
}

Categories