INNER JOIN is not working, i do not get errors - php

$result = mysqli_query($conn,"SELECT * FROM table1 INNER JOIN `table2`
ON `table1`.`id`=`table2`.`id`;");
while ($row = mysqli_fetch_array($result) ){
echo 'name <textarea>'.$row["name"].'</textarea>';
}
on LAb (wampserver) its working i get information about "name", but on really website i not get infromation about "name" .

May some error occur but aren't displayed.
First I suggest you to check the connection:
$conn = mysqli_connect("$host", "$user "my_password", "$DBname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
If it works, check for query errors:
if($result = mysqli_query($conn,"SELECT * FROM table1 INNER JOIN `table2`
ON `table1`.`id`=`table2`.`id`;"))
{
while ($row = mysqli_fetch_array($result) ){
echo 'name <textarea>'.$row["name"].'</textarea>';
}
}
else echo($conn->error);
Other possible causes may are:
ON clause
it's true the condition:
ON table1.id=table2.id
or it should be something like this?
`ON `table1`.`id`=`table2`.`rif_id`
no data to select in table1 or table2
In the live database did you check if there are data to select? May happens to forget to insert data in the live database.
Also, did you tried the query manually in PhpMyAdmin?

I don't know what you trying to collect, but you can use below query to get the record. it will work for you.
"Select t1.* from table1 t1 inner join table2 t2
ON t1.id=t2.id"

Please check the connection may be live connection is different. Also remove semicolon(;) after table2.id. May be your problem is resolved

Related

MySQL SELECT sometimes found nothing even it exists

I have PHP script that runs every 3 hours that gets the amazon mws orders and save it into my database.
But before I insert an order into my table, I check first if the order exist
SELECT COUNT(*) total FROM orders WHERE transaction_id = "XXXXXXXXX"
But sometimes even if an order exist, the query will return 0. If return 0, I will insert the order into my table and it will end up duplicating the data.
This instance happens to me in my other PHP scripts and I don't understand the issue.
You should use something called as EXISTS for checking whether a row exists or not in your case order.
SELECT EXISTS(SELECT * FROM table1 WHERE ...);
SELECT EXISTS(SELECT * FROM tableName WHERE condition);
If your database uses master-slave mode,you can try to force the master to query.
You can also use the “INSERT IGNORE INTO orders ....” to ignore duplicate.
You may have an error in your MySQL query. I created a test table and write some code to print the result of the query which is working correctly.
You may not be using the quotations properly as this is the error most
of the time when you are working with queries in PHP
Here is the code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practise";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$sql = "SELECT count(*) from test where title='Hello'";
$result = mysqli_query($conn,$sql);
$new =mysqli_fetch_array($result);
echo $new[0];
?>
</body>
</html>
And:
Image of the table where I am executing the query
The output against the MySQL query is:
2
The code works perfectly. If you have any other question, please share your code and I'll be more than happy to help you.

Calling a second query if results are empty

I'm calling an INNER JOIN Query to display results from a user if they have information in both tables 1 & 2 - this works fine. However, If said user doesn't have information in both tables then my variables come back undefined.
So I'd like to call my INNER JOIN query and if the rows are empty for Table1, it will call a second query to display the results from Table2.
(Table2 definitely has information stored. Table1 is optional depending on the user)
I also want to display results from Tables 1 & 2 if another user has information in both, I can't seem to get it working. Here's what I have so far;
$sql="SELECT * FROM Table1 INNER JOIN Table2 ON Table1.username = Table2.username WHERE Table1.username='" . $_SESSION['username']['1'] . "'";
$result=MySQL_Query($sql);
if (mysql_num_rows($result)==0)
{
$sql2"SELECT * FROM Table2 WHERE username='" . $_SESSION['username']['1'] . "'";
$result2=MySQL_Query($sql2);
}
while ($rows=mysql_fetch_array($result)($result2))
{
$Username = $rows['username'] ." ";
$Email = $rows['email'] . " ";
}
echo $Email; ?>
You can rewrite your query with an outer join as follows:
select
t1.desired_info
t2.desired_info
from
table2 as t2
left outer join
table1 as t1
on (t2.username = t1.username)
where
t2.username = target_username;
The where clause will narrow the result set down to the user of interest and return 0 rows if the target_username does not exist. t2.desired_info will always come back while t1.desired_info will be null if that user is not present in that table.
You can inspect p1.desired_info in your php code first and if that does not appear then use p2.desired.
Echo the suggestion to use OUTER JOIN, which joins all the selected rows in the left table to matching rows in the right, or to an empty row if there are no matching rows on the right.
Also, I've rewritten to use PDO and a prepared statement, to show you how its done. The values in the variables $dbhost, $dbname, $dbuser and dbpassword are supplied by your code.
<?php
$dsn = "mysql:host=$dbhost;dbname=$dbname";
$dbh = new PDO($dsn, $dbuser, $dbpassword);
$sql = "SELECT *
FROM table2 t1
LEFT JOIN table1 t1 ON t1.username = t2.username
WHERE t2.username = :username";
// prepare() parses and compiles the query. Syntax error come out here.
$stmt = $dbh->prepare($sql);
// bindValue() handles quoting, escaping, type-matching and all that crap for you.
$stmt->bindValue(':username', $_SESSION['username']['1']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_BOTH))
{
$Username = $rows['username'] ." ";
$Email = $rows['email'] . " ";
// and then do something useful with them
}
The use of a prepared statement here gives a significant measure of protection against SQL injection attacks. As usual, I leave error handling as an exercise for the reader.

php PDO script refusing to give useful errors

i've got a script which is meant to run a database query, however when trying to run this script i get the error Fatal error: Call to a member function fetch() on a non-object in /var/www/Quack/doSetup.php on line 209 - 209 being the while loop. I'm 99% sure this corresponds to there being a missing column in my database, however i can't work out which one it doesn't like. I was hoping this try catch system might tell me, it doesn't. Is there any way i can get this too give me more information on what it cannot find?
try{
$query = $db->query("SELECT articles . title FROM articles");
$query = $db->query("SELECT title FROM articles");
$SQLGetLogs = $conn -> query("SELECT `payments`.* , `plans`.`name` AS `planname`, `users`.`username` FROM `payments` LEFT JOIN `plans` ON `payments`.`plan` = `plans`.`ID` LEFT JOIN `users` ON `payments`.`user` = `users`.`ID` ORDER BY `ID` DESC");
while($getInfo = $SQLGetLogs -> fetch(PDO::FETCH_ASSOC)){
echo 'true';
}
}
catch(PDOException $e){echo 'My test failed: ' . $e->getMessage();}
You have to set error mode to throw exception to get them, else only internal error code is set:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The error you're getting is complaining that $SQLGetLogs is not a valid object, meaning that whatever you're setting it to is returning an invalid result.
The SQL statement at
$SQLGetLogs = $conn -> query("SELECT `payments`.* , `plans`.`name` AS `planname`, `users`.`username` FROM `payments` LEFT JOIN `plans` ON `payments`.`plan` = `plans`.`ID` LEFT JOIN `users` ON `payments`.`user` = `users`.`ID` ORDER BY `ID` DESC");
is probably failing or not producing the output you want. You should run the query manually in the database and check the output you get.
Should the $conn here be $db instead?

Joining two tables from different databases

I am aware that there are multiple posts about this, but I was not able to make it work for my code.
As the title suggests I want to join two tables from two different DBs together.
Here is my code:
$dbh1 = mysql_connect("$host", "$username", "$password")or die("cannot connect");
$dbh2 = mysql_connect("$host2", "$username2", "$password2", true)or die("cannot connect");
mysql_select_db("$db_name", $dbh1)or die("cannot select DB");
mysql_select_db("$db_name2", $dbh2)or die("cannot select DB");
//first table
//$sql = mysql_query("SELECT InterestedEntityId, Score FROM users.`user_interests` WHERE UserId= //$userID ORDER BY Score DESC", $dbh1);
//second table
//$sql = mysql_query("SELECT entities.`Name` FROM tags.`entities` WHERE Id = InterestedEntityId", $dbh2);
I want to get the 3 fields mentioned in select statements in one go (I.E. InterestedEntityId, Score, entities.Name)
Any idea on how to join these two tables in one sql query. I tried using inner joins and adding the tablename (as this thread suggested), but the query did not return anything.
Any ideas please?
Something like this should work.
SELECT t1.InterestedEntityId, t1.Score, t2.Name
FROM DB1.users.`user_interests` t1
JOIN DB2.tags.`entities` t2 ON t2.UserId = t1.Id
Note: Use PDO as mysql_* is deprecated and not secure enough.
Pretty much the model is:
SELECT dbName1.TableName1.ColumnName1, dbName2.TableName2.ColumnName2 FROM dbName1.TableName1 JOIN dbName2.TableName2 ON dbName1.TableName1.ColumnName1 = dbName2.TableName2.ColumnName2
Please, don'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.
While it is theoretically possible to join tables from two different databases on the same server, what you are trying to do cannot possibly work because you appear to be accessing two different servers.
In order to get the result set you want you will need to combine them manually.
For example (using PDO):
$dsn1 = "mysql:host=$host;dbname=$db_name";
$dsn2 = "mysql:host=$host2;dbname=$db_name2";
try {
// Create the connections
$db1 = new PDO($dsn1, $username, $password);
$db1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db1->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db1->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db2 = new PDO($dsn2, $username2, $password2);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db2->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db2->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// Get the initial recordset
$sql1 = "
SELECT InterestedEntityId, Score
FROM `user_interests`
WHERE UserId = :userId
ORDER BY Score DESC
";
$stmt1 = $db1->prepare($sql1);
$stmt1->bindParam('userId', $userID, PDO::PARAM_INT);
$stmt1->execute();
// Prepare the statement for the second database
$sql2 = "
SELECT Name
FROM entities
WHERE Id = :entityId
";
$entityId = 0;
$stmt2 = $db2->prepare($sql2);
$stmt2->bindParam('id', $entityId, PDO::PARAM_INT);
// Loop the first result set
$result = array();
foreach ($stmt1 as $row1) {
// Fetch the related data from the second DB
$entityId = $row1['InterestedEntityId'];
$stmt2->execute();
$row2 = $stmt2->fetch();
// Construct the final result row and store it
$result[] = array(
'InterestedEntityId' => $row1['InterestedEntityId'],
'Score' => $row1['Score'],
'Name' => $row2['Name']
);
}
} catch(PDOException $e) {
die($e->getMessage());
}
// The result set you want should now be available
var_dump($result);

Trouble executing multiple-table mysql query from PHP

I am attempting to match rows in a mysql table using the values from table1.column1 and table2.column3 and then copy the value from table2.column2 into table1.column1 for each match. The query below does what I need to do, but only when I execute it manually (through phpmyadmin). When I try to execute it from PHP I receive the error Unknown column table1.column1 in 'field list'. Here is my PHP code:
<?php
mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db($data);
$sql = "UPDATE table1 t1, table2 t2
SET t1.column1 = t2.column2
WHERE t1.column1 = t2.column3";
$result = mysql_query($sql);
if (!$result) {
echo mysql_error();
} ?>
I know that the mysql connection info works because I am able to execute other queries. From my research on the error it seems that I might need backticks around some part of the query but after several tries I can't figure out the correct way.
EDIT 1 - As requested here is the real query:
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.post_type=wp_mf_posttypes.id
Outputs the error
Unknown column 'wp_mf_custom_groups.post_type' in 'field list'
Additional information I just realized might be conflicting with it. Before this happens I also renamed the table using:
RENAME TABLE wp_mf_module_groups TO wp_mf_custom_groups
Maybe since the table was just renamed it cant reference it?
Worked when I added backticks to the columns only after WHERE
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.`post_type=wp_mf_posttypes.id
If query works with PHPmyadmin try this
<?php
$con = mysql_connect($host,$user,$pass) or die('Failed to connect');
$db_selected = mysql_select_db('db_name', $con);
$sql = "UPDATE table1 t1, table2 t2
SET t1.column1 = t2.column2
WHERE t1.column1 = t2.column3";
$result = mysql_query($sql, $con);
if (!$result) {
echo mysql_error();
} ?>

Categories