Don't get value with multi database - php

I have two connection string user DBO:
string1:
try {
$conn1 = new PDO('mysql:host=ip1;dbname=db1','root', '123456');
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
string2:
try {
$conn2 = new PDO('mysql:host=ip2;dbname=db2','root', '123456');
$conn2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
i using join query for join tb1 to tb2:
$stmt = $conn1->prepare(" select db1.*,db2.col1 from db1 left join db2 on db1.col1=db2.col2");
$stmt -> execute();
$result=$stmt->fetchAll();
if(count($result)){
foreach($result as $row){
echo $row[col1]";
}}
else{
Echo 'Not rows';
}
}
catch(PDOException $e){
echo $e->getMessage();
}
It not work.
i have tried $stmt = $conn1,$conn2-> prepare... and it not work too. i wrong something?

You did't mentioned Tables name in your join statement. I think you may want to do something like this :
SELECT * FROM db1.table_name as d1 LEFT JOIN db2.table_name as d2
ON d1.col1 = d2.col2
Try to replace your real Tables name with table_name in db1 and db2 in above statement.

Related

Query failed: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

dbConn.php
<?php
function getConnection()
{
try {
$connection = new PDO("mysql:host=localhost;*****=username", "*****", "*****");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connection;
} catch (Exception $e) {
throw new Exception("Connection error " . $e->getMessage(), 0, $e);
}
}
?>
Admin page:
<?php
try {
require_once("dbconn.php");
$dbConn = getConnection();
$sqlQuery = "SELECT eventID, eventTitle, eventDescription, NE_events.venueID, venueName, location, NE_events.catID, catDesc, eventStartDate, eventEndDate, eventPrice
FROM NE_events
INNER JOIN NE_category
ON NE_category.catID = NE_events.catID
INNER JOIN NE_venue
ON NE_venue.venueID = NE_events.venueID
ORDER BY eventTitle";
$queryResult = $dbConn->query($sqlQuery);
while ($rowObj = $queryResult->fetchObject()) {
echo "<div class='event'>\n
<span class='eventTitle'>{$rowObj->eventTitle}</span>\n
<span class='categoryName'>{$rowObj->catDesc}</span>\n
<span class='venue'>{$rowObj->venueName}</span>\n
<span class='startDate'>($rowObj->eventStartDate)</span>\n
<span class='endDate'>($rowObj->eventEndDate)</span>\n
<span class='price'>($rowObj->eventPrice)</span>
</div>\n";
}
} catch (Exception $e) {
echo "<p>Query failed: " . $e->getMessage() . "</p>\n";
}
?>
I'm trying to retrieve data from MySQL database, but for some reason I get an error saying:
Query failed: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.
As Nigel Ren mentioned you should specify the database name in a DSN string (1st param of PDO constructor).
$connection = new PDO("mysql:host=localhost;dbname=yourDbName", "login", "password");
The error you get clearly states that you don't have DB selected.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
write this line correctly

pdo statement to return more than 1 column in php

I am trying to fetch values from a mysql query using PDO...it works with one column but I need to return 2 columns from the query. Below is the piece of code I have made...
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%'");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$urlean = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
echo $sku;
echo $urlsku;
echo $urlean;
It returns me some array values...which I really can't figure out. Can anyone please help me with this.
If you use fetch() with the PDO::FETCH_ASSOC style it is easy to get both columns:
while($row = $sth->fetch(PDO::FETCH_ASSOC) {
echo $row['prod_url'];
echo $row['ean'];
}
By placing the fetch in a loop all of the rows will be returned which you can then limit as you see fit.
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data[0]['prod_url'];
echo $data[0]['ean'];
Add LIMIT 2 in the query , to get two sets of result :)
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%' LIMIT 2");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_ASSOC, 0);
$urlean = $sth->fetchAll(PDO::FETCH_ASSOC, 1);
print_r($urlsku);
print_r($urlean);

how to know if the SQL query PDO is empty?

I begin to despair, because I do not make a condition, if the result of the request for PDO is empty ...here is the code I use:
try
{
$pdo=new PDO('mysql:host=localhost;dbname=MyDataBase','root','');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql = "SELECT COUNT(*) FROM Mytable WHERE name=".$name;
if ($res = $bdd->query($sql)){
echo" this name exist ";
}
else {
echo "No rows matched the query.";
}
Ues this...
$name= $_POST['name'];
try
{
$pdo=new PDO('mysql:host=localhost;dbname=MyDataBase','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql = "SELECT COUNT(*) FROM Mytable WHERE name=".$name;
$res = $pdo->query($sql);
$row = $res->fetchColumn();
if ($row){
echo" this name exist ";
}
else {
echo "No rows matched the query.";
}
It should $pdo instead in $bdd in query statement...basically a typo..thats all

How to catch exact sql error in php pdo statement

I am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);

How can I use prepared statements combined with Transactions with PHP?

My goal is to use a transaction and a prepared statement simultaneously, to achieve both integrity of data, and prevention of SQL injection.
I have this:
try {
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$cnx->query("SELECT * FROM users WHERE username=$escaped_input");
$cnx->query("SELECT * FROM othertable WHERE some_column=$escaped_input_2");
$cnx->commit();
}
catch (Exception $e){
$cxn->rollback();
echo "an error has occured";
}
I would like to incorporate the query as one would with a prepared statement:
$stmt=$cxn->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($user_input));
$stmt_2=$cxn->prepare("SELECT * FROM othertable WHERE some_column=?");
$stmt_2->execute(array($user_input_2));
How can I achieve that?
Edit
I get this error:
PHP Parse error: syntax error, unexpected T_CATCH
Here is my updated code:
try
{
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$stmt=$cnx->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($username));
$cnx->commit();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $stmt->userid;
}
catch(Exception $e) {
if (isset($cnx))
$cnx->rollback();
echo "Error: " . $e;
}
Just call "execute" after you call "beginTransaction".
Where you call "prepare" doesn't really matter.
Here's a complete example:
http://php.net/manual/en/pdo.begintransaction.php
EXAMPLE:
try {
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$stmt=$cxn->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($user_input));
$stmt_2=$cxn->prepare("SELECT * FROM othertable WHERE some_column=?");
$stmt_2->execute(array($user_input_2));
$cnx->commit();
}
catch (Exception $e){
$cxn->rollback();
echo "an error has occurred";
}
PS:
1) I'm assuming, of course, that $user_input and $user_input_2 are available immediately. You don't want your transaction hanging open unnecessarily long ;)
2) Based on your comment reply above, I think you might be confusing "execute" and "begin tran/commit". Please look at my link.
3) Do you even need a transaction? You're just doing two "select's".
4) Finally, why not do one "join" (or union, if compatible) instead of two "select's"?
try
{
$cnx = new PDO ($dsn,$dbuser,$dbpass);
$cnx->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction ();
$stmt = $cnx->prepare ("SELECT * FROM users WHERE username=?");
$stmt->execute(array($username));
$cnx->commit();
while ($row = $stmt->fetch (PDO::FETCH_OBJ)){
echo $row->userid;
}
}
catch (Exception $e) {
if (isset ($cnx))
$cnx->rollback ();
echo "Error: " . $e;
}
}
Did you mean this?
try {
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$stmt=$cnx->prepare("
SELECT * FROM users, othertable
WHERE users.username=?
AND othertable.some_column=?");
$stmt->execute(array($user_input,$user_input_2));
$cnx->commit();
}
catch (Exception $e){
$cnx->rollback();
echo "an error has occured";
}
That is assuming that the two tables data does not have duplicate field names, otherwise you're going to have to use:
SELECT users.field1 as u_field1, othertable.field1 as o_field1 FROM users, othertable
WHERE users.username=?
AND othertable.some_column=?

Categories