No database selected when trying to setup query in php - php

Ok i get the following error "No database selected" when trying to run a query in php. the connect file in in the connect.inc.php file and that returns no error. i an learning php so any help i thank you. Also to note the query works in phpmyadmin panel with no errors
<?php
require 'connect.inc.php';
$sql = "SELECT `name`, `address`, `city` FROM `customers` ORDER BY `id`";
if ($sql_run = mysql_query($sql)) {
echo 'Success.';
} else {
echo mysql_error();
}
?>

The mysql library is deprecated, use mysqli or PDO.
With mysqli, you can also select the database directly when you're creating the connection (and I recommend doing that when possible, if you're only working with one database) :
$db = mysqli_connect("<host>","<username>","<password>","<database>");
Replace <database> with the DB you want to use.

Either use in your connect.inc.php the mysql_select_db function just after mysql_connect:
mysql_select_db('your_database_name');
or add the database name in every query:
$sql = "SELECT `name`, `address`, `city` FROM `your_database_name`.`customers` ORDER BY `id`";
Note that the mysql library is deprecated and you should use mysqli or PDO. If you're learning, run away from any "tutorial" that still uses these deprecated functions.

hope you write write script to connect DB in this way or you can try this....
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
}else{
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
}
}

This is a basic example i have kind of filled in with your code. You will need to fill in the vars with FILL THIS as values.
<?php
$host = "FILL THIS";
$db = "FILL THIS";
$user = "FILL THIS";
$pass = "FILL THIS";
$link = mysql_connect($host,$user ,$pass);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $link);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
require 'connect.inc.php';
$sql = "SELECT `name`, `address`, `city` FROM `customers` ORDER BY `id`";
if ($sql_run = mysql_query($sql,$link)) {
echo 'Success.';
} else {
echo mysql_error();
}
mysql_close($link);
?>

Related

Can't query MySQL Database

I'm trying to query a database using php5.6, I can't get this query to work, the error seems to be with
$response = #mysqli_query($dbc, $query) OR die('nope'. mysql_error());
This is my query php file:
<?php
require 'db.php';
$query = "SELECT * FROM USERS";
$response = #mysqli_query($dbc, $query) OR die('nope'. mysql_error());
if ($response){
echo 'Query successful!';
} else {
echo 'Error - query unsuccessful';
}
?>
This is my db connection file:
<?php
error_reporting(E_ALL);
$DB_User = 'user';
$DB_Passwd = 'pass';
$DB_Host = 'localhost';
$DB_Name = 'myDB';
$dbc = mysqli_connect($DB_Host,$DB_User,$DB_Passwd,$DB_Name);
if (!$dbc) {
die('Could not connect: ' . mysqli_error());
}
I've updated the files to all use mysqli and removed the #, but it's still not connecting or showing errors, still just throwing a 500. I'm not sure where to go from here...
in this line you should use mysqli_connect() instead of mysql_connect()
$dbc = #mysql_connect($DB_Host,$DB_User,$DB_Passwd,$DB_Name)
and in case of #mysql_connect() your syntax will be like this
$dbc = #mysql_connect($DB_Host,$DB_User,$DB_Passwd);
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('foo', $dbc);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
// NOTE THAT
mysql is deprecated since 5.5 and deleted in php 7
so it is not recommended to use it

SQL in PHP failure

If the value of the result is 0 it has to go to 'cid_check_firstdep.php' otherways (if its 1) it has to go to 'cid_check_depwid.php'.
It has to work, but i don't know why it doesn't. I've tried what i could that i think would be possible to fix it, but nono.
Code:
<?php
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$sql = "SELECT validated FROM users WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($sql,$con);
if ($sql<'1')
{
mysql_close($con);
header('Location: /ucp/cid_check_firstdep.php');
}
else
{
mysql_close($con);
header('Location: /ucp/cid_check_depwid.php');
}
?>
or do i have to use :
if ($sql=='0')
?
|||
#John Conde
<?php
if(! get_magic_quotes_gpc() )
{
$withdraw = addslashes ($_POST['withdraw']);
}
else
{
$withdraw = $_POST['withdraw'];
}
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$__sql = "SELECT cardvalue FROM users WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($__sql,$con);
if ($__sql<'5000000')
{
header('Location: /ucp/includes/withdraw_fail.php');
mysql_close($con);
}
else
{
$_sql = "UPDATE users SET Bank=Bank + '$deposit' WHERE Username='".($_SESSION['username'])."'";
mysql_select_db("server");
mysql_query($_sql,$con);
$sql = "UPDATE users SET cardvalue=cardvalue +- '$deposit', thismonth_withdraw=thismonth_withdraw + '$deposit', lastwithdraw = Now() WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($sql,$con);
mysql_close($con);
header('Location: /ucp/includes/withdraw_done.php');
}
?>
You're checking the wrong variable for your SQL result. You're using the variable containing your query instead of the variable you never assigned to capture the result of mysql_query(). You also want to use mysql_num_rows() to see how many results were returned.:
$result = mysql_query($sql,$con);
if ($result && mysql_num_rows($result) == 1) {
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Hi Morgan I change your code according to my knowledge. I think this will help you to work done.
If you found any match to the username "count($return_data)" will get 1.
Thanks.
<?php
$con = mysql_connect("localhost","root","password");
$select_db = mysql_select_db("bluecard");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$sql = "SELECT validated FROM users WHERE username='".($_SESSION['username'])."'";
$query = mysql_query($sql,$con);
$return_data = array();
while($rows = mysql_fetch_array($query)){
$return_data[]=$rows;
}
if (count($return_data)<=1)
{
mysql_close($con);
header('Location: /ucp/cid_check_firstdep.php');
}
else
{
mysql_close($con);
header('Location: /ucp/cid_check_depwid.php');
}
?>

PHP insert query not working

<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')");
if(mysql_query($sql)){
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>
</body>
</html>
I am trying to insert these values into my database into the table users but when I run the code it keeps on saying "item addition failed" but I am not sure why, there is no problem with the database connection as I have already tested that, and I am not sure what's wrong with my insert query?
There are some problems in your code. Firstly you do query twice. Secondly are you sure your db name is $db = '#######'; change it to proper name.
To check if query was ok and if rows were added use mysql_affected_rows() to check errors use mysql_error()
Also change your sql engine to PDO or mysqli which are better.
Please mind that Mysql_* functions are depracated. That is why I've given you example how to use db connection in PDO.
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######'; //CHANGE IT TO PROPER NAME WHERE TABLE users IS!
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l')") or die(mysql_error());
if(mysql_affected_rows()>0)
echo "Item added successfully.<br/>";
else
echo "Item addition failed.<br/>";
?>
I'll give you proper example how to do it with PDO cause if you still learn it'll help you :)
PDO example
<?php
$dsn = 'mysql:dbname=YOUR_DB_NAME;host=localhost';
$user = 'users';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
$count = $dbh->exec("INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l');");
echo $cout ? "Item added successfully" : "Item addition failed";
} catch (PDOException $e) {
echo 'Failed: ' . $e->getMessage();
}
?>
The secure and good way to insert values is using prepared statements.
To create prepared statement you use
$stmt = $dbh->prepare("INSERT INTO users (name, email) VALUES(?,?)");
$stmt->execute( array('user', 'user#example.com'));
You can learn more here
You are using mysql_query twice. Change your code to:
$sql = "INSERT INTO users VALUES ('' ,'l','l','l','l', 'l','l')";
try this.your called function mysql_query() twice.
on second time you passed it the result_set instead of query.
<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users
VALUES('' ,'l','l','l','l', 'l','l')");
if($sql){
print "Item added successfully.<br/>";
}
else { print "Item addition failed.<br/>"; }
?>
</body>
</html>
This should help you debug, you should look into PDO instead though... And of course remember to use the correct credentials, i presume you have removed them for safety :-)
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')", $connect) OR die(mysql_error());
if($sql)
{
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>

converting mysql to the new mysqli API

I am trying to convert my mysql command to fit the new standard of mysqli and I will post the scripts and then the questions. I already created the table in the database.
config.php:
$dbhost="databasehost";
$dbusername="username";
$dbpassword="password";
$dbname="databasename";
$connect = mysql_connect($dbhost, $dbusername, $dbpassword);
mysql_select_db($dbname,$connect) or die ("Could not connect to database");
?>
insert.php:
include("config.php");
if (isset($_POST[firstname]) && isset($_POST[lastname]) && isset($_POST[age])) {
$sql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
mysql_query($sql, $connect);
header("Location: add.htm");
// "1 record added";
}
else {
echo "no record added";
}
if (!mysql_query($sql,$connect))
{
die('Error: ' . mysql_error());
}
mysql_close($connect);
?>
view.php:
<?php
include("config.php");
$sql = mysql_query("SELECT * FROM Persons");
if ($sql) {
while($results = mysql_fetch_array($sql)) {
echo $results['FirstName'] . ', ' . $results['LastName'] . ', ' . $results['Age'] . '<br/>';
}
} else {
die('Error: ' . mysql_error());
}
mysql_close($connect);
?>
First, how do I modify the scripts to use the mysqli instead of mysql?
Second, when using the above script, when I add something from the
form it always add duplicate entry. How do I prevent that?
Third, to prevent sql injection what can I add to the code? I know
for php attach I can use "$firstname =
trim(strip_tags(stripslashes($_POST['firstname'])));" Will that also
cover sql injection since I am sanitizing the input?
kindly read through the official manual for the migration :
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi

Php mysql create database if not exists

I want to create a database. Why is not the db created with this code?
$dbname = 'regulations_db';
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
echo "Database $dbname already exists.";
}
else {
mysql_query("CREATE DATABASE '". $dbname ."'",$con);
echo "Database $dbname created.";
}
This is working, but I think the first one is the best practice:
if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
Just do a simple mysql_select_db() and if the result is false then proceed with the creation.
As an example, check out the first answer here by another very smart StackOverflower.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Three steps to fix this:
Don’t specify the database name when connecting.
Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
Call mysqli_select_db($link, 'php1') to make that the default database for your connection.
If you're using MySQLi Object-oriented method, you can use following code, this code is similar to previous answer and only the method is different, I just put this because if anyone using MySQLi Object-oriented method, you can use this code directly.
$servername = "localhost";
$username = "mysql_user";
$password = "user_password";
$dbName = "databaseName";
// Connect to MySQL
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If database is not exist create one
if (!mysqli_select_db($conn,$dbName)){
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
}else {
echo "Error creating database: " . $conn->error;
}
}
Furthermore you can refer W3school site here.
Good Luck! :D

Categories