I would like to ask for help with converting my mysql_* query to prepared statement using PDO technology. There are many of them which I cannot find on the internet how to solve them properly - mostly advanced ones like this one for example:
mysql_query("SELECT * FROM pet_auction JOIN people ON (pet_auction.pet=people.guid)
LEFT OUTER JOIN login.account ON (pet_auction.winner=login.account.id)
WHERE active=1 AND seller=$userid ORDER BY id DESC");
How to succesfully convert it to PDO STMT using these?:
$people = new PDO("mysql:host=localhost;dbname=people", "myuser", "mypass");
$login = new PDO("mysql:host=localhost;dbname=login", "myuser", "mypass");
Thank you all I rather will not try else it would be false because i tested already ... I have no idea how to convert LEFT OUTER JOIN and multiple databases together.
You do not need to open a pdo object for each database. Just give myuser grant access to both login and people databases. Then query like so:
$dbh = new PDO("mysql:host=localhost;dbname=people", "myuser", "mypass");
$stmt= $dbh->prepare("SELECT * FROM pet_auction JOIN people ON (pet_auction.pet=people.guid)
LEFT OUTER JOIN login.account ON (pet_auction.winner=login.account.id)
WHERE active=1 AND seller=:userid ORDER BY id DESC");
$stmt-> execute(array(':userid' => $userid));
$variable = $stmt->fetch(PDO::FETCH_ASSOC);
$dbh = new PDO($dsn, "myuser", "mypass");
$select = $dbh->prepare("SELECT * FROM `table`");
$select -> execute();
$variable = $select->fetch(PDO::FETCH_ASSOC);
where $dsn is a string containing 'mysql:dbname=racerost_reekris_db;host=localhost'
the query can contain any mySQL query including joins.
Related
When I run the code below, it returns nothing. When I explicitly type a string in the place of the '?', it will return the expected result but using the prepared version has not worked for me thus far. I do not believe there is any kind of versioning issue as using prepared statements for INSERT queries has worked for me in the past. What might be the problem here with the prepared statement?
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE '%?%';";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_GET['searchterm']));
$results = $stmt->fetchAll();
print_r($results);
You are preparing the value so it isn't behaving as if you just put the string inside of the query.
When preparing a string you don't need to add " or ', that is done for you. You need to add the %'s into the value that you are escaping.
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array("%{$_GET['searchterm']}%"));
$results = $stmt->fetchAll();
print_r($results);
i am having issue with inner join. in phpmyadmin i have 3 tables:
1 - proyects
2 - users
3 - proyects-users (relation table)
i am sending to php an idproyects i want to list all available users on that proyect So...
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbuser, $dbpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users u INNER JOIN proyects-users pu on pu.id = u.id WHERE pu.idproyect='$justavariable'");
$stmt->execute();
$result = $stmt->fetchAll();
}
You should be using parameters as indicated by other comments - but also you should avoid using '-' in any names in the database. So proyects-users would usually be proyects_users.
You could put quotes `proyects-users` around the name, but it's just not standard or convention to use '-' in any names.
You should also be checking that anything you do actually works, as any execute could fail for all sorts of reasons, so usualy
if ($stmt->execute()) {
$result = $stmt->fetchAll()
}
I'm having a problem running prepared queries on a MSSQL database using PDO. I can connect to the database and run SELECT queries with no parameters, but now I'm trying to run a simple SELECT query with one parameter, :user. However, the code does not return any values, despite the fact that there definitely is a database row with that value in. Here's the code I'm using:
$db = new PDO('dblib:host='.$dbHost.';dbname='.$dbName.';charset=utf8mb4',$dbUser, $dbPass);
$stmt = $db->prepare('SELECT * FROM customer WHERE email_address = :user ');
$stmt->bindValue(":user", $_SESSION["username"], PDO::PARAM_STR);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
I receive no output from the var_dump. I know that in the database there is a correct row, so I tried:
$stmt = $db->prepare("SELECT * FROM customer WHERE email_address = 'the#email.com'");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
And yet still no value was returned. Am I doing something wrong with PDO? If I type this exact query into the query bar it runs.
you forgot to execute your query.
right after the paramter binding, put this code:
$stmt->execute();
Ok, I'm an idiot. Forgot to execute the query. Amended code for people in the same predicament:
$db = new PDO('dblib:host='.$dbHost.';dbname='.$dbName.';charset=utf8mb4',$dbUser, $dbPass);
$stmt = $db->prepare('SELECT * FROM customer WHERE email_address = :user ');
$stmt->bindValue(":user", $_SESSION["username"], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
$id=$_GET['previd'];
$SQL = "select * from pro where prId=".$id;
I am new to PHP. Can anyone explain what happens here?
This is taking the value of the GET (url) passed variable "previd".
Something like http://example.com/page.php?previd=123 would set
previd to 123.
Next it sets the variable $id to 123.
Next $SQL gets set to select * from pro where prId=123
Next a nefarious person can go to http://example.com/page.php?previd=;DROP TABLE pro and your database has now been deleted.
This is why people use sanitization and prepared statements.
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
More Info
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);