I am new to php and had chosen to stick to PDO format. I have been able to set up a workable registration and login system, but my challenge is fetching data from my database which would be used in other page of the user profile page I created. I had tried all the many examples and methods I was able to get on the internet but there are not working, or rather I don't know how to use it, where I want to insert the variable will still be empty.
The only fetch function I was able to get will select all the row, for instance, if it is email, it will fetch all the registered emails in the database which is not suppose to be. The email should only be for the user whose profile is opened.
Here are the codes. I am sure someone will help me figure this out. Thanks
$data = $pdo->query("SELECT * FROM databaseName")->fetchAll();
//this one is in the body where i want to insert the email
foreach ($data as $row) {
echo $row['email']."<br />\n";
}
I tried everything my little knowledge of php but all to no avail. If i decide to use any other one, nothing will show.
You can try other alternative to achieve the same,
$stmt = $pdo->query('SELECT * FROM databasetable');
while ($row = $stmt->fetch())
{
echo $row['email'] . "\n";
}
If you are only interested in the email from the returned results, I would look to do the following:
$stmt = $pdo->query('SELECT `email` FROM databasetable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['email'] . "\n";
}
Or
$stmt = $pdo->query('SELECT `email` FROM databasetable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC))
foreach($data as $row)
{
echo $row['email'] . "\n";
}
If you want to check that the data coming back is good, I would add a "print_r($data);".
You can just take the first element of the results.
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
or use fetch()
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetch(PDO::FETCH_ASSOC);
I´ve also put a LIMIT at the end of your query, so you dont fetch unneeded data.
Unless I am missing something then surely you should be specifying a where in your SQL query, why would you get the entire database and loop through it until you find the email you want?
When you redirect the logged in user you must(or if you aren't then you should) be passing something about the user, e.g setting the userid in the session. Then you can use this to create more useful profile data with a query that says select email from table where userid = :userid - then when you fetch the result you will have the data you need.
Naturally I can't write the exact query without knowing your structure but getting a whole tables worth of data every time is unscalable
I have been doing MYSQL just fine for a while now but am trying to learn how to do all that i know with PDO; what I am struggling with now is a simple SQL select, and then I loop through all the rows and dump the corresponding column values into a variable; and then I can do something with the variables for that row while in the loop; here is the way I used to do it with mysql:
$result42 = mysql_query("SELECT * FROM members");
while($row = mysql_fetch_array($result42, MYSQL_BOTH))
{
$user_id=$row['user_id'];
$user_name=$row['user_name'];
$email=$row['email'];
// do something with info for each user; like maybe echo their info...
}
I am attempting to do the same thing with PDO but not finding anything quite like what I am trying to do…
I found some code which uses fetchall and fetchassoc and seems to be putting it in an array; but I have no idea how to loop through the array and get each value on the row like i did with mysql above; and I am not even sure if the PDO that i have here can do that…
this is what I have:
$stmt = $dbh->prepare("SELECT * FROM members");
$products = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
}
}
All i want to do is end up cycling through each row getting the values, doing something with them and then moving on to the next row…
Can anyone help with this? Thanks...
I have a variable $search and I want to search for records containing the $search in multiple columns
$query="Select * from products where name LIKE ? OR color LIKE ?"
$stmt = $this->pdo->prepare($query);
$results=$stmt->execute(array("%$search%","%$search%"));
but when I try to execute print_r($results);, I get nothing displayed except for a '1'.The problem perhaps is binding of the $search variable to the query.So I am curious whether there's a way to handle such a situation and what's the best working alternative.Thanks
$results is the success status of the PDOStatement execution; the returned rows are still in the $stmnt object. You need to iterate over the returned rows and print the individually.
while ($row = $stmnt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
will work.
You can also use the following:
while ($row = $stmnt->fetch()) {
echo $row['YOUR COLUMNS NAME HERE'].'<br>';
}
or use bind columns:
$stmt->bindColumn('COLUMN 1 NAME', $variable1);
$stmt->bindColumn('COLUMN 2 NAME', $variable2);
$stmt->bindColumn('COLUMN 3 NAME', $variable3);
//...... GO ON LIKE THIS
$stmt->execute();
I am trying to make connections to two different databases so my script should work as follows
Find all orders for the current logged in customer where the order state is complete, it is a virtual product and it has a juno order id (this query works fine)
Collect all of order ids that have been found and store them in an array (this works fine)
now connect to sales_order_items and for each item that is part of an order id check to see if the database has a url download link,
if not i will connect to an api --
the problem is when i want to make my second connection i seem to lose all the values that are stored in the $orderIds array.
i have been looking for solutions but i am pretty new to the zend framework
any help would be much appreciated
my script is as follows
$conn = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $conn->query('select * from sales_flat_order WHERE customer_id='.$session->getCustomerId().' AND state="complete" AND is_virtual=1 AND juno_order_id!="null"');
$orderIds=array();
foreach ($result as $orderId)
{
$orderIds[]=$orderId[entity_id];
$itemsonOrder=$conn->query('select * from sales_flat_order_items WHERE order_id='.$order[entity_id]);
}
// value of first array $orderIds gets lost if i make annother connection using $conn
echo 'items on order';
print_r($itemsonOrder);
echo '<pre>';
print_r($orderIds);
echo '</pre>';
Well you aren't done with the first query yet when you are connecting with the second query. Go ahead and finish with the first query, then start the second one. Try something more like this...
$conn = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $conn->query('select * from sales_flat_order WHERE customer_id='.$session->getCustomerId().' AND state="complete" AND is_virtual=1 AND juno_order_id!="null"');
$orderIds=array();
foreach ($result as $orderId)
{
$orderIds[]=$orderId[entity_id];
}
foreach ($orderIds as $orderId)
{
$itemsonOrder=$conn->query('select * from sales_flat_order_items WHERE order_id='.$orderId);
}
Also, you should probably make sure you are using parameters when doing queries. Concatenating sql strings like that can be dangerous (leaves you open to vulnerabilities sometimes). For example,
$conn->query('select * from sales_flat_order_items WHERE order_id='.$orderId);
should be changed to
$conn->query('select * from sales_flat_order_items WHERE order_id=?', array($orderId));
Also, do you really need to "select *"??? I mean, just select the columns you need.
I have two dynamic tables (tabx and taby) which are created and maintained through a php interface where columns can be added, deleted, renamed etc.
I want to read all columns simulataneously from the two tables like so;-
select * from tabx,taby where ... ;
I want to be able to tell from the result of the query whether each column came from either tabx or taby - is there a way to force mysql to return fully qualified column names e.g. tabx.col1, tabx.col2, taby.coln etc?
In PHP, you can get the field information from the result, like so (stolen from a project I wrote long ago):
/*
Similar to mysql_fetch_assoc(), this function returns an associative array
given a mysql resource, but prepends the table name (or table alias, if
used in the query) to the column name, effectively namespacing the column
names and allowing SELECTS for column names that would otherwise have collided
when building a row's associative array.
*/
function mysql_fetch_assoc_with_table_names($resource) {
// get a numerically indexed row, which includes all fields, even if their names collide
$row = mysql_fetch_row($resource);
if( ! $row)
return $row;
$result = array();
$size = count($row);
for($i = 0; $i < $size; $i++) {
// now fetch the field information
$info = mysql_fetch_field($resource, $i);
$table = $info->table;
$name = $info->name;
// and make an associative array, where the key is $table.$name
$result["$table.$name"] = $row[$i]; // e.g. $result["user.name"] = "Joe Schmoe";
}
return $result;
}
Then you can use it like this:
$resource = mysql_query("SELECT * FROM user JOIN question USING (user_id)");
while($row = mysql_fetch_assoc_with_table_names($resource)) {
echo $row['question.title'] . ' Asked by ' . $row['user.name'] . "\n";
}
So to answer your question directly, the table name data is always sent by MySQL -- It's up to the client to tell you where each column came from. If you really want MySQL to return each column name unambiguously, you will need to modify your queries to do the aliasing explicitly, like #Shabbyrobe suggested.
select * from tabx tx, taby ty where ... ;
Does:
SELECT tabx.*, taby.* FROM tabx, taby WHERE ...
work?
I'm left wondering what you are trying to accomplish. First of all, adding and removing columns from a table is a strange practice; it implies that the schema of your data is changing at run-time.
Furthermore, to query from the two tables at the same time, there should be some kind of relationship between them. Rows in one table should be correlated in some way with rows of the other table. If this is not the case, you're better off doing two separate SELECT queries.
The answer to your question has already been given: SELECT tablename.* to retrieve all the columns from the given table. This may or may not work correctly if there are columns with the same name in both tables; you should look that up in the documentation.
Could you give us more information on the problem you're trying to solve? I think there's a good chance you're going about this the wrong way.
Leaving aside any questions about why you might want to do this, and why you would want to do a cross join here at all, here's the best way I can come up with off the top of my head.
You could try doing an EXPLAIN on each table and build the select statement programatically from the result. Here's a poor example of a script which will give you a dynamically generated field list with aliases. This will increase the number of queries you perform though as each table in the dynamically generated query will cause an EXPLAIN query to be fired (although this could be mitigated with caching fairly easily).
<?php
$pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
function aliasFields($pdo, $table, $delim='__') {
$fields = array();
// gotta sanitise the table name - can't do it with prepared statement
$table = preg_replace('/[^A-z0-9_]/', "", $table);
foreach ($pdo->query("EXPLAIN `".$table."`") as $row) {
$fields[] = $table.'.'.$row['Field'].' as '.$table.$delim.$row['Field'];
}
return $fields;
}
$fieldAliases = array_merge(aliasFields($pdo, 'artist'), aliasFields($pdo, 'event'));
$query = 'SELECT '.implode(', ', $fieldAliases).' FROM artist, event';
echo $query;
The result is a query that looks like this, with the table and column name separated by two underscores (or whatever delimeter you like, see the third parameter to aliasFields()):
// ABOVE PROGRAM'S OUTPUT (assuming database exists)
SELECT artist__artist_id, artist__event_id, artist__artist_name, event__event_id, event__event_name FROM artist, event
From there, when you iterate over the results, you can just do an explode on each field name with the same delimeter to get the table name and field name.
John Douthat's answer is much better than the above. It would only be useful if the field metadata was not returned by the database, as PDO threatens may be the case with some drivers.
Here is a simple snippet for how to do what John suggetsted using PDO instead of mysql_*():
<?php
$pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$query = 'SELECT artist.*, eventartist.* FROM artist, eventartist LIMIT 1';
$stmt = $pdo->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch()) {
foreach ($row as $key=>$value) {
if (is_int($key)) {
$meta = $stmt->getColumnMeta($key);
echo $meta['table'].".".$meta['name']."<br />";
}
}
}