MYSQL - SELECT from different databases - php

How can I select data in the same query from two different databases into the same server?
This is what I'm doing, but my query doesn't works:
$sqlquery = "SELECT * FROM database_2.table_2 WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2";
$result = mysql_query($sqlquery);
$number = mysql_numrows($result);
$i = 0;
if ($number < 1) {
print "DOH";
}else{
while ($number > $i) {
$content = mysql_result($result,$i,"database_2.table_2.data_3");
print "$content";
$i++;
}
}

The problem is not about different databases.
Your WHERE clause references the field database_1.table_1.data_1 which was not supplied in the FROM clause.
Didn't you mean something like
SELECT *
FROM database_2.table_2
JOIN database_1.table_1
ON (database_2.table_2.some_field = database_1.table_1.some_other_field)
WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2
?
Also,
echo mysql_error();
after your failed query - this will give you a clue about what's wrong.

isn't numrows underscored?
$number = mysql_num_rows($result);
http://php.net/manual/en/function.mysql-num-rows.php

try this
SELECT * FROM database_2.table_2 t2 INNER JOIN database_1.table_1 t1
ON t1.data_1 = t2.data_2

Related

Selecting rows from multiple tables

I would like to know what the fastest way is to make the following SQL call using PHP. I am using procedural mySQLi.
$dcount = "SELECT max(id) FROM deposits";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(id)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
//second query
$ucount = "SELECT max(int) FROM anothertable";
$result2 = mysqli_query($conn,$ucount);
if (mysqli_num_rows($result2) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(int)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
Is there a way to make the execution faster than like this, maybe to echo the results from both queries after the first if statement?
It just seems rather long to me.
Thanks in advance.
SELECT max(id) as max_id, (SELECT max(int) as max_int FROM anothertable) as max_int
FROM deposits
Not tested, but something like it should work
$dcount = "
SELECT max(id) as max,'deposit' as table_name FROM deposits
UNION
SELECT max(id) as max,'another' as table_name FROM anothertable
";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row["table_name"].":".$row["max"]."\n";
}
} else {
echo '0';
}
SELECT d.max(id) as d_max_id, a.max(int) as a_max_int FROM deposits as d JOIN anothertable as a ON d.id = a.id;
is what you need for multiple tables
$row['d_max_id']
will give you deposits.max(id) now
You have to edit the d.id = a.id accordingly to what you want the two tables to match on
If you cant join try this:
SELECT max(id) as max_id, (SELECT max(int) FROM anothertable) as max_int FROM deposits;
SELECT max(id) as max_id, max(int) as max_int FROM deposits ,anothertable

Fetching data from relational database in codeigniter

I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:
$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'");
$data['relation'] = $query->result_array();
Now using groupid result I want to query the first table i.e. table1
I have tried the following methods, without any success:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2
The above code only returns the last row of the table1 however I am looking for all the results.
When I run the above code inside the "for" loop, it shows me a count of 33:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}
I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.
Thanks,
Utpal
$ok = array();
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
print_r ($id);
echo "<br>";
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'][$ii]= $query1->result_array();
}
//print_r($data1['group']);
$fine = array_merge($data, $data1);
print_r($fine);
You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above

Multiple Mysqli Select Statement, echo separated results

I have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco

PHP MySQL with two query

I need to do a SELECT * FROM table_X , the problem is table_X is the result of another query, I don't know how to do it, perhaps with two loop, something like this :
<?php
$query1 = mysql_query("SELECT * FROM table_ref");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query(" SELECT * FROM '$name' ");
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
?>
The tables are all similar & I can't do joint there's no keys. So what I want is to show only the results of the second query from each results of the first query !
So, what's your structure? I don't understand. You have column table_name where are listed a lot of tables? If so, just use backquotes on your $name:
$query2 = mysql_query(" SELECT * FROM `$name` ");
Apart from the obvious that has been pointed out in the comments, you're overwriting $row in the second loop.
Also, you're trying to read an array ($data) that is not defined.
The following will work much better (but still isn't ideal):
$query1 = mysql_query("SELECT `table_name` FROM `table_ref`");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query("SELECT `itime` FROM `$name`");
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
just change your quotes to have the query ready to be started
change
$query2 = mysql_query(" SELECT * FROM '$name' ");
to
$query2 = mysql_query(" SELECT * FROM `".$name."` ");
i would also rather sugest to check this part
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
you already used variable $row to fetching previus query so better to change to something else, look like $data is matching your needs because you already used but you did not declare it
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
Try this query:
select x.* from ( SELECT table_name FROM table_ref) as x

Get number of fields in mysql table

How can I get number of fields(сolumns) in mysql table with PHP or just some kind of mysql query? Is there a way to do this without SELECT * FROM table_name and mysql_num_fields()? Maybe there is a way with one mysql query?
SELECT COUNT(*) totalColumns
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table1' AND
TABLE_SCHEMA = 'databaseName'
SQLFiddle Demo
Use the below query to get no of fields in table,
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'database_name'
AND table_name = 'tbl_name'
#user1858864 All the above answers are fine but I just wanted to give it to you in php using pdo .
And I did up vote your question and their answers because everything seems to be relevant to me
A big thanks to #JW. For editing
<?php
try {
$con = new PDO('mysql:host=localhost;dbname=mydb;charset=utf-8','root','');
} catch(PDOException $e){
echo 'Connection failed'.$e->getMessage();
}
#count in pdo
$count = ("SELECT count(*) FROM table_name ");
$result =$con->prepare($count);
$result->execute();
$number= $result->fetchColumn();
echo $number;
#count in pdo
?>
$query = "select book_name from tbllibrary "; $result = mysql_query($query);
//while loop to display mysql table field values in html text boxes
$i = 0;
while ($row = mysql_fetch_row($result))
{
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
next($row);
$y = $y + 1;
}
$book_name=$c_row;$i = $i + 1;
}
echo 'There are ' . $i. ' books available in the Library</p>';
Here the variable i will store total no.of columns for the row named book_name. You can also use the variable $book name for the future use but it is not mandatory.
You can use the following query
SELECT count(*) FROM table_name

Categories