error: No database selected when displaying data on website - php

My name is Anna and I'm building a website with a festival calendar! People can add festivals when they're logged in. But now is my question, how can I display what people put in my database. I found the following code on this website, but when I put it in my script, I get the error that there's no database selected. But I do have a database selected (Festivals) ?
$sql = "SELECT festival_name, festival_organisator, festival_begin FROM Festivals WHERE festival_id=3";
$result = mysql_query($sql) or die(mysql_error());
$festival_name = $festival_organisator = $festival_begin = array();
while($row = mysql_fetch_assoc($result)) {
$festival_name[] = $row['festival_name'];
$festival_organisator[] = $row['festival_organisator'];
$festival_begin[] = $row['festival_begin'];
}
I hope anybody can help me! Thanks in advance

You have not yet connected to the database itself
Query selecting from the table Festivals does not mean that you've selected the Festivals database, those are two very different things.
The database Festivals contains all the tables (table Festivals, table x, etc).
The table Festivals contains data which you can query (festival_name, festival_organisator, etc).
Now you must connect
Taking a look at the documentation is always a good choice, let's see how you can connect to and select a database:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
You should be connected to the database, having access to the selected database through $link.
mysql_query($sql, $link)
But don't do it!
Unless you must, but cute puppies will die :(
You shouldn't be using mysql_* in the first place though since it's no longer supported. Instead you should be using PDO or mysqli to achieve your task. It may sound or appear trickier at first but it's actually rather simple:
Related answer on how to query with PDO.
The PDO documentation provide nice examples on how to query.
The mysqli_* documentation provide nice examples on how to query.

Related

how to connect two mysql databases in two servers

i want to connect two mysql databases one is located in localhost and other one is located in a server
here is what i have done so far and i am not getting either error or data
<?php
$con=mysql_connect('120.247.201.8:3306','root','root');
$con1=mysql_connect('localhost','root','');
//mysql_connect('localhost','root','');
if(!$con){
die('Try Again');
}
if(!$con1){
die('Try Again');
}
mysql_select_db("iot",$con1);
mysql_select_db("lora_gateway",$con);
$result =mysql_query("SELECT lora_gateway.`server_log`.`created_at`, lora_gateway.`server_log`.`temperature`FROM iot.`device` inner JOIN `lora_gateway`.`server_log` on `lora_gateway`.`server_log`.`gateway_Id` = `iot`.`device`.`gatewayId` where iot.`device`.`deviceId`='23' ORDER BY lora_gateway.`server_log`.`created_at` desc");
$num= mysql_num_rows($result);
print_r($num);
?>
This is a solution for multiple servers, connections and DBs.
Two or more MySQL 5 db servers
Two or more locations (local and/or anything else)
Two or more different databases
Two or more tables and fields
Tested and Works fine :-)
//Define your database connections and select your database want to use. In this example I use two connections and two DBs. But you can use more than two.
<?php
//MySQL Server 1
$dbhost1 = "127.0.0.1";
$dbuser1 = "dbuser1";
$dbpassword1 = "dbpass1";
$db1 = "database1";
$connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
mysql_select_db($db1,$connection1);
//MySQL Server 2
$dbhost2 = "xxx.xxx.xxx.xxx";
$dbuser2 = "dbuser2";
$dbpassword2 = "dbpass2";
$db2 = "database2";
$connection2 = mysql_connect($dbhost2,$dbuser2,$dbpassword2) or die (mysql_error());
mysql_select_db($db2,$connection2);
//The SQL statement
$sql =" SELECT database1.tablename1.fieldname1 AS field1, database2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tablename2";
//Execute query and collect results in $results
$results = mysql_query($sql);
//Print result until end of records
while($rows = mysql_fetch_array($results)){
print $rows["field1"]." | ".$rows["field2"]."<br>";
}
?>
First of all, try to accustom yourself to using PDO or at least the mysqli_ functions. It's the future. :)
mysql_query's second parameter, the connection link, is optional. If omitted, it uses the last connection opened with mysql_connect. (See php.net Documentation)
Ergo, always use $con or $con1 as 2nd parameter in order to use the correct connection.
Then, provided that your queries are correct, it should work as expected.
what about to add connection to mysql_query() ?
$result = mysql_query("SELECT lora_gateway.`server_log`.... desc", $con);

mysql Show tables returns all +1 with TABLES "number of rows" as first value

When i recently wanted to list all tables in a database in php i made the simple MySQL query:
$tables_query = mysql_query('show tables');
while ($test = mysql_fetch_array($tables_query)) {
echo "Table: {$test[0]}<br />";
}
The first result is
TABLES 105
address_book
I don't have a table called "TABLES 105" but the mysql_num_rows also shows, that there is 105 results, even that my database only contains 104 table
If i try to request "show tables" directly on the MySql server, it works fine and i get 104 rows as result. It also worked before and i can't seem to find anything about this, so im hoping someone can help me in here.
It also affect when i call directly to the mysql server. I got access with an other user login for an other database, on the same server and here is no issues at all.
Its questionable how that 105 got there in the first place, most likely this is caused by that mysql_num_rows function that you mentioned as fetch_array actually fetches the rows, but here's one on MySQLi, stop using MySQL anymore:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'username', 'password', $db);
$tables_query = mysqli_query($con, "SHOW TABLES FROM {$db}");
while($table = mysqli_fetch_assoc($tables_query)) {
echo $table["Tables_in_{$db}"], '<br/>';
}
An alternative way of course is to delve into information_schema:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'root', '', $db);
$tables_query = mysqli_query($con, "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$db}'");
while($table = mysqli_fetch_array($tables_query)) {
echo $table['TABLE_NAME'], '<br/>';
}

(MySQL/PHP) Inserting data into MySQL table using PHP

I'm developing a web app for movie reviews. I am writing the page where reviews are created and am having issues with the data for a new review being uploaded to the MySQL database. When I submit a new review I get the created successfully message, however the database remains unchanged.
The POST data is gathered by forms located on the same page.
Connect.php:
<?php
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('mydb');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
Here's my PHP code:
<?php
session_start();
require("connect.php");
if(isset($_SESSION['critic_name'])){
$movie_id=NULL;
if (isset($_POST['reviewmovie']) && isset($_POST['rating'])){
$movie_title = $_POST['reviewmovie'];
$review_title = $_POST['review_title'];
$movie_id = mysql_query("SELECT movie_id FROM Movies WHERE 'movie_title'=".$_POST['reviewmovie']." ") or die(mysql_error());
$mem_id = mysql_query("SELECT mem_id FROM Members WHERE 'critic_name'=".$_SESSION['critic_name']." ") or die(mysql_error());
$rating = $_POST['rating'];
$comments = $_POST['comments'];
$result = mysql_num_rows($movie_id);
$result2 = mysql_num_rows($mem_id);
if(!$result && !$result2){
$query = mysql_query("INSERT INTO `Reviews` (review_id, rating, comments, mem_id movie_id, review_title) VALUES ('$rating', '$comments', '$mem_id', '$movie_id', '$review_title')");
if($query){
$msg = "Review Created Successfully.";
}
}
}
}
?>
Remove the quotes from both WHERE 'movie_title' and WHERE 'critic_name' those are column names and not variables. If you absolutely want to wrap them in something, use backticks `` `.
Plus, change ".$_POST['reviewmovie']." to '".$_POST['reviewmovie']."' and ".$_SESSION['critic_name']." to '".$_SESSION['critic_name']."'
You also forgot a comma in between mem_id and movie_id (which will break your query).
(review_id, rating, comments, mem_id movie_id, review_title)
^ // <- right there
Change it to:
(review_id, rating, comments, mem_id, movie_id, review_title)
Sidenote: Your present code is open to SQL injection. Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

How to get data from a different database and save it to another database

I don't know if this problem of mine is possible. Is it? I have a library system. I add and edit new books in the Catalog Database. In other words, the Catalog Database is for adding/editing books only. I have another Database (not table) for Borrowing Books. I want to store these books, which are viewed through Catalog DB, to Borrowing DB.
I have a snippet for getting data from Catalog DB
error_reporting(0);
$con = mysql_connect("localhost","root","");
mysql_select_db("catalog", $con);
$acc_number=$_GET["acc_number"];
$query="select * from branch where acc_number = '$acc_number'";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//echo $row[1];
}
<textarea name="title" disabled><?php echo $row[1];?></textarea>
And a button for the submission (store to borrowing database). If button is clicked, it's where my problem occurs. I just got a blank page after submitting it. Here is my process.php:
$con = mysql_connect("localhost","root","");
mysql_select_db("catalog", $con);
$acc_number = $_POST['acc_number'];
$title = $_POST['title'];
$sql = mysql_query("select * from books where acc_number='$acc_number'");
while($row=mysql_fetch_array($sql)){
$con = mysql_connect("localhost","root","");
mysql_select_db("borrowing", $con);
$query="INSERT INTO borrowers (title) VALUES ('$title')";
mysql_query($query);
if($query){
header("Location:../librarysystem/books.php");
}
}
You need to create two sql connections, one for each DB. Then simply get the data from one DB (perform operations, if required) and write to the second DB.
First, I suggest that you use MYSQLI or DO since MYSQL is deprecated.
These are suggestions not a fix.
Use only one connect function, you don't need two of them just use the same variable $con.
Add some error checks in there to make sure you are connecting properly
$sql = mysql_query("select * from books where acc_number='$acc_number'") or die ("error message here");
For this
$query="INSERT INTO borrowers (title) VALUES ('$title')";
mysql_query($query);
if($query){
header("Location:../librarysystem/books.php");
}
Try
$query=mysql_query("INSERT INTO borrowers (title) VALUES ('$title')") or die("Could not insert...");
if($query){
header("Location:../librarysystem/books.php");
}
You have two approaches for this:
Create two separate DB connections and manipulate data there. Passing $conn as connection to MySQL queries will work.
Use the same database using different DB prefixes. Say for example, for first DB it should be
mb_ (Manage Books)
and
bb_ (Borrow Books)
If I were at your place, I would have preferred second approach.

mysql php : switching between mysql databases is slow

In my php script which connects to mysql, I have to query 2 databases in the same script to get different information. More specifically Faxarchives in one database and Faxusers in the other.
In my code I query faxusers and then foreach user, I query Faxarchives to get the user history.
I might do something like:
function getUserarchive( $userid) {
$out= "";
$dbname = 'Faxarchive';
$db = mysql_select_db($dbname);
$sql = "select sent, received from faxarchivetable where userid = '" . $userid . "'";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['sent'] . " " . $row['received'];
}//end while
}//end if query
return ($out);
}//end function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'Faxusers';
$db = mysql_select_db($dbname);
$sql="select distinct userid from faxuserstable";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['userid'] . ":" . getuserarchive($row['userid']);
}//end while
}//end if query
I'm guessing the switching between databases for each user is causing the slowness. Anyways how i can improve the speed of the processing?
thanks in advance.
You have several problems. First, your function, getUserarchive, pulls back all rows all the time. Looks like you forgot to restrict your SQL to only a specific userid. That's a big cause of your speed issues.
Another option would be to pass in all userids you are interested in. Rewrite the SQL as SELECT sent, received FROM faxarchivetable WHERE userid IN (...), which means you'd have one select to pull back all info from your faxarchivetable, instead of one per each userid.
Finally, if both databases are on the same MySQL server, you could just do a single select to pull in all the information:
SELECT Faxusers.faxuserstable.userid, sent, received FROM Faxusers.faxuserstable JOIN Faxarchive.faxarchivetable ON Faxusers.faxuserstable.userid = Faxarchive.faxarchivetable.userid
Are you aware that you can query tables in separate databases by qualifying the tablename?
For example, I think you can get all your information in a single SQL query like this:
SELECT sent, received
FROM Faxarchive.faxarchivetable
WHERE userid IN ( SELECT DISTINCT userid FROM Faxusers.faxuserstable );
Oh, this is the same point ChrisInEdmonton makes. I didn't notice his answer.

Categories