Issue with JOIN in PHP MySQL - php

Having a bit of a struggle here with adding JOINs to a query. I am connecting to two separate databases (on the same server). For this reason, I am writing this mysqli simply and will convert to a prepared statement once it's working.
// REMOVED: DB VARIABLES
$conn = new mysqli($servername, $username, $password, $db_connective_data);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$conn2 = new mysqli($servername, $username, $password, $db_resources);
if ($conn2->connect_error) { die("Connection failed: " . $conn2->connect_error); }
$sql = "SELECT * FROM downloads LEFT JOIN resource_data ON downloads.resource_id_REF=resource_data.resource_id WHERE downloads.user_basics_id_REF='$user_id'";
$result = $conn->query($sql);
$number_of_download_rows_returned = mysqli_num_rows($result) -1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resource_id_REF[] = $row['resource_id_REF'];
$download_date[] = date('Y-m-d', strtotime($row['download_date']));
$resource_title[] = $row['resource_title'];
$resource_title_link[] = str_replace(" ", "-", $row['resource_title']);
}
}
$conn->close();
A query without a JOIN works fine (albeit without returning the resource_title):
$sql = "SELECT * FROM downloads WHERE downloads.user_basics_id_REF='$user_id' ORDER BY downloads.download_date DESC";
What am I missing here? The first code sample will return no results. The second one will return three.
Any assistance is greatly appreciated.
Here is a list of the different database names that I reference. As I stated, some data is in the "connective_data" db and some is in the "resources" db.
$db_connective_data = "connective_data";
$db_lists = "lists";
$db_messaging = "messaging";
$db_resources = "resources";
$db_users = "users";
I can't seem to get two of them connected. Am I missing something strikingly obvious here?

There is no need to create 2 connections if the databases are located on the same mysql server. You can simply reference tables from another database as databasename.tablename.
As a result, you can join 2 tables from 2 different databases as:
$sql = "SELECT * FROM yourdatabase1.downloads LEFT JOIN yourdatabase2.resource_data ON yourdatabase1.downloads.resource_id_REF=yourdatabase2.resource_data.resource_id WHERE yourdatabase1.downloads.user_basics_id_REF='$user_id'";
Obviously, you need to substitute your real database names for yourdatabase1 and yourdatabase2 in the above query.
Update: Are you sure you need so many databases? These seem to be tables to me, not databases.

Related

Filtering SQL queries

I'm creating a php query trying to filter from a specific SQL table specific Events.
For example table is called tbl_events and one specific column is showing user ID data let's call it USER_ID
The table has more than 50.000 data lines so if I try and filter it with php it takes TOO much time. So my try is to filter it with SQL before I show the query to the php table and see if it becomes faster.
I want to filter the query in order NOT to show the ones who have an ID let's say "2"
My code is the following (and its obviously not working)
$GetEventsList = GetDataWhere("tbl_events","USER_ID!=2",0);
I'm new in SQL commands so be patient :)
Is this what you're looking for?
Query:
SELECT * FROM tbl_events WHERE USER_ID != '2'
So to implement this with php I would suggest:
$servername = "Your server ip here";
$username = "Database_username_here";
$password = "Database_password_here";
$dbname = "Database_name_here";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_events WHERE USER_ID != '2'";
// Run $sql content as sql script in db.
$result=$conn->query($sql);

PHP script, select on server 1 and insert on server 2 if iD doesn't exist (i.e. new records)

We have a phone system database on one server that we cloned/dumped to our local server, but now we need to keep our version updated. Obviously, tables and schema are the same, I just want to run this scheduled script to update with new records that don't exist on the local table (i.e. records that were created since last update).
Below is a test select/insert block. The select query worked on it's own originally, but now I've modified it to use a loop with hopes of using numrows and a foreach to capture everything in the select.
The session table has about 35 columns so I'm looking for the best way to go about this without having to declare every column. I originally tried to do this using update on duplicate key or insert/ignore using a not exists but I don't really know what I'm doing.
Basically, once I select everything, if my table on server 2 doesn't contain a record with the SESSIONID primary key, I want to insert it. I just need some assistance creating this loop script.
Example:
if the table on server 1 has 2 rows with sessionID 12345, and 12346, but my table on server 2 only has up to sessionID 12344, I want to insert the whole records for those two IDs.
//Defining credentials
$servername = "";
$username = "";
$password = "";
$servername2 = "";
$username2 = "";
$password2 = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
//Query to select * from Session table on server 1
$query1 = "select * from cdrdb.session";
$results = mysqli_query($conn1, $query1);
foreach ($results as $r => $result) {
$stmt1 = mysqli_prepare($conn2, "insert into ambition.session a where not
exists(a.SESSIONID)");
mysqli_stmt_execute($stmt1) or die(mysqli_error($conn2));
}

php Update sql and Query

I want to do a query in php, output the data on the page and then modify it in the database.
How do I do that?
Currently I do it like this but it dose not work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM pics WHERE id = '$id'";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
$dir = $row["dir"];
$likes = $row["likes"];
}
$sqlq = "UPDATE pics SET likes='$likes+1' WHERE id='$id'";
$conn->query($sqlq);
$conn->close();
But the like dose not add to the database.
If you echo your $sqlq out using
echo $sqlq;
you'll see that the '$likes+1' isn't doing what you expect.
You could really simplify it by doing
$sqlq = "UPDATE pics SET likes=likes+1 WHERE id='$id'";
which removes any risk of two users updating the database at teh same time overwriting each other.
But you should really check out using "parameterized queries" as that would solve all your problems (and may your queries safer). Check the examples in the manual http://php.net/manual/en/mysqli-stmt.bind-param.php

Simple and effective way to echo the result of a query in PHP?

I'm new to MySQL and PHP and I m struggling to echo my queries (the results not the text!)
I have searched for this but nothing seems to work properly, the best I managed to do was echoing the text of the query. I might have some fatal mistakes but here is my code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("atoma",$dbhandle)
or die("Could not select atoma");
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
echo $r['maximum'];
$sql2 = "SELECT COUNT(DISTINCT NAME) FROM thema2";
$sql1 = "SELECT AVG(GRADE) FROM thema3";
mysql_close($dbhandle);
?>
I get nothing as a result.
I have these 3 queries and all I want is just to print their results. I've written code for echoing only one of the 3 since the other 2 will be echoed as the first one I want to believe.
Your code seems incorrect because, the connection is mysqli and fetching is using mysql
$conn = new mysqli($servername, $username, $password, $dbname);
....
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
A full example of W3Schools
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
When you use max, avg, etc you pull only one result, so with the $result[0] you has the result you want
Edit:
If you're new, maybe you come to see read this:
http://codular.com/php-mysqli
So A) would leave using an outdated way to call the database, and B) with this in principle bringing the first row you would have the result of AVG, MAX, etc. when only one row which returns you if you make this types of sentences ;)

how to connect more than two databases i.e (3 Databases) in php [duplicate]

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
I know how to connect to a single database using:
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.
Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx functions or see the answer below from #Troelskn
You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2) e.g.:
mysql_query('select * from tablename');
Other options
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
Keep one connection open and call mysql_select_db() to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
I just made my life simple:
CREATE VIEW another_table AS SELECT * FROM another_database.another_table;
hope it is helpful... cheers...
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
$Db1 = new mysqli($hostname,$username,$password,$db_name1);
// this is connection 1 for DB 1
$Db2 = new mysqli($hostname,$username,$password,$db_name2);
// this is connection 2 for DB 2
Try below code:
$conn = mysql_connect("hostname","username","password");
mysql_select_db("db1",$conn);
mysql_select_db("db2",$conn);
$query1 = "SELECT * FROM db1.table";
$query2 = "SELECT * FROM db2.table";
You can fetch data of above query from both database as below
$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
$data1[] = $row;
}
$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
$data2[] = $row;
}
print_r($data1);
print_r($data2);
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2',$dbh2);
mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.
Unless you really need to have more than one instance of a PDO object in play, consider the following:
$con = new PDO('mysql:host=localhost', $username, $password,
array(PDO::ATTR_PERSISTENT => true));
Notice the absence of dbname= in the construction arguments.
When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. You can switch between databases by using the USE dbname statement via the PDO::exec() method.
$con->exec("USE someDatabase");
$con->exec("USE anotherDatabase");
Of course you may want to wrap this in a catch try statement.
You might be able to use MySQLi syntax, which would allow you to handle it better.
Define the database connections, then whenever you want to query one of the database, specify the right connection.
E.g.:
$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection
$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection
Then to query them on the same page, use something like:
$query = $Db1->query("select * from tablename")
$query2 = $Db2->query("select * from tablename")
die("$Db1->error");
Changing to MySQLi in this way will help you.
You don't actually need select_db. You can send a query to two databases at the same time. First, give a grant to DB1 to select from DB2 by GRANT select ON DB2.* TO DB1#localhost;. Then, FLUSH PRIVILEGES;. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2 etc. (Don't forget that you need 'root' access to use grant command)
if you are using mysqli and have two db_connection file. like
first one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB1**);
second one is
define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define(**'DB2**','database_name1');
$connMitra = new mysqli(HOST, USER, PASS, **DB2**);
SO just change the name of parameter pass in mysqli like DB1 and DB2.
if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function
<?php
// Sapan Mohanty
// Skype:sapan.mohannty
//***********************************
$oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
$NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
mysql_select_db('OLDDBNAME', $oldData );
mysql_select_db('NEWDBNAME', $NewData );
$getAllTablesName = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
$getAllTablesNameExe = mysql_query($getAllTablesName);
//echo mysql_error();
while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {
$oldDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
$oldDataCountResult = mysql_fetch_object($oldDataCount);
$newDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
$newDataCountResult = mysql_fetch_object($newDataCount);
if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
echo "<br/><b>" . $dataTableName->table_name . "</b>";
echo " | Old: " . $oldDataCountResult->noOfRecord;
echo " | New: " . $newDataCountResult->noOfRecord;
if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
echo " | <font color='green'>*</font>";
} else {
echo " | <font color='red'>*</font>";
}
echo "<br/>----------------------------------------";
}
}
?>

Categories