In this project, I have a dynamic columns which I stored in mapping table. Now usnig following query, I can fetch all the column names I need.
$db = new PDO("...");
$statement = $db->prepare("select column_name from mapping_table");
$list = $statement->fetch();
$matches = implode(',', $list);
Now from this result, I need to make a query. My question is how can I pass this $matches to the column_name of second query.
$db1 = new PDO("...");
$qry1= $db1->prepare("select {$matches} from table1");
$result= $qry1->fetch();
Try something like this:
db = new PDO("...");
$statement = $db->query("select column_name from mapping_table");
$list = $statement->fetchAll(PDO::FETCH_COLUMN);
$matches = implode('`,`', $list);
And then:
$db1 = new PDO("...");
$qry1= $db1->query("select `$matches` from table1");
$result= $qry1->fetch();
Related
This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.
i'm wanting to display the actual header_titles (a row in each of my tables) from all the tables in my database
My current query
select column_name, table_name from information_schema.columns
where column_name in (
select column_name from information_schema.tables
where table_schema='site'
) and
column_name='header_title';
At the moment the query returns 'header_titles' 12 times (the amount of tables in my db with the field, and obviously the table names. I'm not sure how to get the values of each of the header_titles
A very trivial example
UPDATE - column values are now being printed on the screen
$query = "SELECT table_name FROM information_schema.tables AS tbl
WHERE EXISTS(SELECT 1 FROM information_schema.columns AS col
WHERE tbl.table_name = col.table_name AND column_name = 'header_title')";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
while($row = mysqli_fetch_row($result))
{
$q = 'SELECT header_title FROM '.$row[0];
$r = mysqli_query($conn, $q) or trigger_error(mysqli_error($conn), E_USER_ERROR);
$index = 0;
while($data = mysqli_fetch_row($r))
{
$index++;
echo "Table = ".$row[0].", row = ".$index.", HEADER_TITLE = ".$data[0].PHP_EOL;
}
}
I have done this type of SELECT many times, but this time I can't get it to work. Any ideas, please?
$Name = "Dick";
$conn = mysqli_connect($server, $dbname, $dbpw, $dbuser);
$sql = "SELECT id FROM table WHERE $Name = table.first_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$customer_id = $row['id'];
Database::disconnect();
echo "customer id = " . $customer_id;
If you really DO have a table named table it would be more appropriate to use back ticks around the name since the word TABLE is a reserved word in MySQL. You should also use single quotes around your variable if it contains a string:
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
Other possible reasons if the query still doesn't work for you:
Make sure you have the connection parameters in the right order. It should be: mysqli_connect($server, $dbuser, $dbpw, $dbname).
You should be using fetch_array() instead of fetch_assoc() if you expect a one row result.
You are mixing PROCEDURAL STYLE with Object Oriented Style when using mysqli_connect() instead of mysqli(), at the same time using $result-> which is object oriented style. You should decide one style and stick with it.
This would be the procedural style of your query:
$Name = "Dick";
$conn = mysqli_connect($server, $dbuser, $dbpw, $dbname); // NOTE THE CHANGED ORDER OF CONNECTION PARAMETERS!
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
mysqli_free_result($result); // FREE RESULT SET
mysqli_close($conn); // CLOSE CONNECTION
And this would be the object oriented style:
$Name = "Dick";
$conn = new mysqli($server, $dbuser, $dbpw, $dbname);
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
$result->free(); // FREE RESULT SET
$conn->close(); // CLOSE CONNECTION
I would recommend naming your table something else than table since it's a reserved word and could get you into parsing problems. The same goes with field names. More reading: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
More about mysqli_fetch_array() and differences in procedural style and object oriented style use: http://php.net/manual/en/mysqli-result.fetch-array.php
$sql = "SELECT id FROM table WHERE '$Name' = table.first_name";
You simply need to concat the variable like this:
$sql = "SELECT id FROM table WHERE " . $Name . " = table.first_name";
The following works...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
$items[] = $row->nid;
}
dsm($items);
However, when I want to select the content type "venue" from the "type" column in the same database tables, I get errors using the following...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid AND type = venue';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
$items[] = $row->nid;
}
dsm($items);
DOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'venue' in 'where clause': SELECT nid FROM {node} WHERE uid = :uid AND
type = venue; Array ( [:uid] => 1 )
Im ovbiously not understanding something here. The column is called "type", im not asking it to look for a column called "venue" am i?
When comparing a column to a string you need to wrap the string with quotes, if you dont, the optimizer will see this as a column(unless its a number) . Try this:
$sql = "SELECT nid FROM {node} WHERE uid = :uid AND type = 'venue'"
In making database queries in Zend Framework 2, how should I be sanitizing user submitted values? For example, $id in the following SQL
$this->tableGateway->adapter->query(
"UPDATE comments SET spam_votes = spam_votes + 1 WHERE comment_id = '$id'",
\Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE
);
You can pass parameters when you execute..
$statement = $this->getAdapter()->query("Select * from test WHERE id = ?");
$result = $statement->execute(array(99));
$resultSet = new ResultSet;
$resultSet->initialize($result);
You can also pass them directly to the query method
$statement = $this->getAdapter()->query(
"Select * from test WHERE id = ?",
array(99)
);
$result = $statement->execute();
$resultSet = new ResultSet;
$resultSet->initialize($result);
Both will produce the query "Select * from test WHERE id = '99'"
If you want to use named parameters:
$statement = $this->getAdapter()->query("Select * from test WHERE id = :id");
$result = $statement->execute(array(
':id' => 99
));
$resultSet = new ResultSet;
$resultSet->initialize($result);
If you want to quote your table/field names etc:
$tablename = $adapter->platform->quoteIdentifier('tablename');
$statement = $this->getAdapter()->query("Select * from {$tablename} WHERE id = :id");
$result = $statement->execute(array(
':id' => 99
));