This question already has answers here:
MYSQL PHP No Database Selected - Can't Find Error
(2 answers)
Closed 7 years ago.
Here is my php code
<?php
error_reporting(E_ALL);
class ll{
function ll(){
include "sql.php";
}
function getUser($ID) {
$sql="select * FROM users where ID=$ID";
$res = mysql_query($sql) or die (mysql_error());
$obj = mysql_fetch_object($res);
return $obj;
}
function setOfflineALL() {
$sql="update users set online=0";
mysql_query($sql);
}
}
$services = new ll();
$services->setOfflineALL(); // THIS WORKS !
$services->getUser(1); // THIS GIVES error: No database selected
?>
and sql.php is:
<?php $hostname_con1 = "localhost";
$database_con1 = "db1";
$username_con1 = "root";
$password_con1 = "mypass";
$con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_con1);
mysql_set_charset('utf8',$con1);
?>
sql.php is correct (no error)
setOfflineALL works fine (no error)
getUser raises "no database selected error !", however I do select one with mysql_select_db
I do use php5.4
Any clue ?
I also tried:
function getUser($ID) {
$hostname_con1 = "localhost";
$database_con1 = "db1";
$username_con1 = "root";
$password_con1 = "mypass";
$con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_con1);
mysql_set_charset('utf8',$con1);
$sql="select * FROM users where ID=$ID";
$res = mysql_query($sql) or die (mysql_error());
$obj = mysql_fetch_object($res);
return $obj;
}
And still have error:
No database selected
You should try this:
mysql_select_db($database_con1, $con1);
And you should give your database variable to your query too:
mysql_query("query", $con1);
And I strongly advise you not to use mysql but use PDO or mysqli
PDO
Mysqli
Related
This question already has answers here:
PHP global in functions
(7 answers)
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 3 years ago.
I was just organizing one of my codes and notice that leaving the connect-mydb.php out of a function, it doesnt work.
I always thought the include would be loaded prior to any of the functions.
connect-mydb.php
<?php
$server = 'localhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydb';
$mysqli = new mysqli($server, $user, $pass, $db);
?>
testdb_out.php (doesnt work)
<?php
include 'connect-mydb.php';
function UpdateDB() {
echo "working\n";
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
echo 'success';
}else{
echo 'failed';
}
}
UpdateDB();
?>
testdb_within.php (works)
<?php
function UpdateDB() {
include 'connect-mydb.php';
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
echo 'success';
}else{
echo 'failed';
}
}
UpdateDB();
?>
In testdb_out, shouldnt the include be loaded prior to the function? That works in other programming languages.
I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}
I'm sure the question is easy to answer, but I don't get it.
When I try to connect in a function it throws me an "Access denied for user''#'localhost'" error. It looks like the array isn't available in the array, because the error says I didn't enter a username and password.
The code is:
$config["mysql_host"] = "localhost";
$config["mysql_user"] = "myusername";
$config["mysql_pass"] = "mypass";
$config["db_name"] = "mydb_name";
$config["event_tname"] = "tablename";
function get_events(){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die ("Error, please contact the provider!"/* . mysqli_error()*/); //execute
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
events(); //just an example: call the function
What do I have to change at the array?
Regards,
Franz
At first you should consider using mysqli object-orientated. There is no reason to use procedural style anymore.
Secondly global PHP variables are not available inside of functions, therefore you need to pass the array to the function as explained in the other answer.
See this article for more information on PHPs variable scope.
Imho the best solution would be to use a class for your application and store the config as private attributes. Methods of that class will then have access to the attributes.
just add global $config; inside your function as
function get_events(){
global $config;
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events(); //ju
or pass the config param to function
function get_events($config){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events($config); //ju
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I saw questions about this problem on overflow, but i can't find the decision.
This is last variant of my code.
Sorry but I absolutely 0 in php :(
<?php
$host = "*****";
$user = "*****";
$pass = "******";
$databaseName = "******";
$tableName = "product";
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($con, $databaseName);
$sql = ( "SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row(mysqli_query("$con", "$sql")) )
{
$data[] = $row;
}
echo json_encode( $data );
mysqli_close($con);
?>
why I receive error
Catchable fatal error: Object of class mysqli could not be converted to string in /home/**/public_html/php/api.php on line 15
on this string
while ( $row = mysql_fetch_row(mysqli_query("$con", "$sql")) )
You need to run the query and get a result before looping -
$sql = ( "SELECT * FROM $tableName");
$result = mysqli_query($con, $sql); // remove quotes from variables, only query once
$data = array();
while ( $row = mysqli_fetch_row($result) )....// loop through results
There are many more improvements you can make to the code. You're assuming the query will always work, you shouldn't. You're assuming that you'll always connect to the database, you won't. You're mixing database methods, you shouldn't (mysql_ vs. mysqli_)
The changes can be seen in the comment below
$con = mysqli_connect($host,$user,$pass,$databaseName ); //add the database name
//$dbs = mysqli_select_db($con, $databaseName); //you can remove this then
$sql = ( "SELECT * FROM $tableName");
try //add a try catch to handle error
{
$result = mysqli_query($con,$sql); //add result variable
if($result) //check if result was successful
{
while($row = mysqli_fetch_array($result)) //use mysqli_fetch_array instead
{
$data[] = $row;
}
}
else
{
throw new Exception('Unable to get data:'.mysqli_error($con)); //error message
}
}
catch(Exception $e)
{
echo $e->getMessage(); //print out error
}
mysqli_free_result( $result ); //free the resources after used
mysqli_close($con);
echo json_encode( $data );
As the above commentors mention your specific error is coming because of this line:
$row = mysql_fetch_row(mysqli_query("$con", "$sql"))
If you look at the specific error it mentions you're trying to convert a MySQLi object into a string. mysqli_query expects you to pass in a string and a mysqli connection and a query (http://php.net/manual/en/mysqli.query.php). When you have "$con" passed in, you're trying to convert the $con object (a mysqli class) into a string and this is breaking.
In regards to the rest of the code there are other issues mentioned above and in comments, but this will fix the specific error you have
mysqli_query($con, "$sql")
Though you don't need the quotes around $sql either, since it's already a string
<?php
$host = "*****";
$user = "*****";
$pass = "******";
$databaseName = "******";
$tableName = "product";
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($con, $databaseName);
$sql = ( "SELECT * FROM $tableName");
$data = array();
$dataquery= mysqli_query($con, $sql);
while ( $row = $dataquery->fetch_array() )
{
$data[] = $row;
}
echo json_encode( $data );
mysqli_close($con);
?>
I've never had to use mysqli until today and cannot seem to get this right. What I want is a simple function that will accept a mysql procedure call and have it return those results.
When I started using these procedures, I noticed that the old way of querying the database, using mysql_query, would no longer get me the expected results; one procedure would successfully return and the other would not. After reading the manual and several other examples out there, I found that the reason for this odd behavior was because the results need to be buffered then cleared. I have tried several ways of doing this and have been unsuccessful.
What I have so far works if I create another instance of the mysqli object and will get me both results however, I don't think it's right that I should have to instantiate 20 different objects to get back 20 different queries.
Again, what I want here, is to have a single function that I can feed a procedure to and have the results returned back.
$mysqli = new mysqli('host','user','password','test');
$rs = $mysqli->query('CALL titles()');
while($row = $rs->fetch_object())
{
print_r($row);
}
$mysqli2 = new mysqli('host','user','password','test');
$rs2 = $mysqli2->query('CALL colours()');
while($row2 = $rs2->fetch_object())
{
print_r($row2);
}
you can make a class for this:
db.php // A db class. Call this you perform a query.
<?php
class MyConnection{
var $db_host = 'Localhost';
var $db_user = 'mYUserName';
var $db_password = 'myPassword';
var $db_name = 'mYDB';
var $connection;
function Connect(){
$this->connection = #mysqli_connect($this->db_host, $this->db_user, $this->db_password)
or
die("Error: ".mysqli_connect_error());
mysqli_select_db($this->connection, $this->db_name);
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
function Disconnect(){
mysqli_close($this->connection);
}
function ExecSQL($query){
$result = mysqli_query($this->connection, $query)
or
die('Error: '.mysqli_error($this->connection));
return $result;
}
}
?>
Implementation:
include "db.php";
$conn = new MyConnection;
$conn->Connect();
$rs = $conn->ExecSQL('CALL titles()');
while($row = $rs->fetch_object())
{
print_r($row);
}
$rs2 = $conn->ExecSQL('CALL colours()');
while($row2 = $rs2->fetch_object())
{
print_r($row2);
}
$conn->Disconnect();