Oracle/PHP oci_fetch_all() issue - php

Pretty new to PHP using Oracle. I'm following examples online. I'm using this example 1 from the official site. My issue is, it displays all the records like I want, but it's missing the column/field names. Does anyone now how to alter this so that it includes the headers? (ex, my employee table would have... First Name, Last Name....) Thanks
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employee');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
echo "<tr>\n";
foreach ($col as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>

Most DBMS(I haven't worked with them all so I can't say "all") systems have a separate table that stores this sort of meta information, so you'd want to query it. In Oracle, it's stored as a dictionary, probably in some sort of table header data or meta info (I really don't know Oracle's underlying structure well) and it's called user_tab_columns
So what do ya do? Query it as though it were a table.
SELECT * FROM user_tab_columns WHERE TABLE_NAME='employee'
However, I don't know why you'd want to query this after the fact given your code, as you already know the column names and could easily just hardcode them in.

Related

How can I group values from a database using <td> and rowspan?

So, I am reading some values from a database. Such as 'result', 'team', 'league' from a database. I am trying to display, in a <table>, results of the specific team grouped by league, something like this:
That is assuming my database contains the following data:
result1 team1 league1
result2 team1 league1
result100 team1 league2
result101 team1 league2
result88 team1 league2
I have tried a lot of stuff and yet I can't get it to work. Also, the league cell must have a rowspan equal to the number of results detected in the specific league. This can be done with mysql_num_rows, but I don't know exactly where to place it. So how can I get this table to work? Thanks a lot!
Groupng the output by league is a simple matter of doing a break-sort on the results of your query. Since your question doesn't
include your table schema, or any php code, I've made some assumptions about your table, and will leave opening the connection to
your DB, and executing the sql statement to you.
$qstr = "SELECT league, team, event
FROM table
ORDER BY league, team, event";
// Execute query, get results into associative array $allrows
$league = "";
$col1 = "";
$col2 = "";
echo "<table>\n";
foreach($allrows as $rowno => $row) {
if($league != $row['league']) {
if($league != "") {
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
}
$league = $row['league'];
$col1 = $league;
$col2 = "";
}
$col2 .= $row['team']." got ".$row['event']."<br />\n";
}
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
echo "</table>\n";
I have try'd some way and it worked for me I hope it works for you...
Look at the code:
$db = new PDO('mysql:host=localhost;dbname=you_dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT league, result, team FROM matches_info';
$stmt = $db->query($sql);
echo "<table border=\"1\">";
while($row = $stmt->fetch()){
echo '<tr>
<td rowspan="3">'.$row['pcid'].'</td>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].' </td></tr>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].'</td></tr></tr>';
}
echo "</table>";
It is very basic you can Add more functions to improve the functionality of it.

OCI8 OCI_FECTH_ARRAY returning no values no errors

Hi I am running a simple SQL statement to pull data and display using OCI_FETCH_ARRAY() with no luck. PHP doesnt log any error in error_log, or show no error message but shows just the blank page.
Table definition is as below:
Below is the SQL and i can run on SQL developer to pull relevant data:
$sql="SQL Here";
Error handling while running OCI_PARSE and OCI_EXECUTE functions below:
$stid = oci_parse($conn,$sql);
$error_msg_conn= oci_parse($conn,$sql);
if (!$error_msg_conn) {
$e = oci_error($conn);
echo htmlentities($e['message']);
}
$error_msg_stmt = oci_execute($stid);
if (!$error_msg_stmt) {
$e = oci_error($stid);
echo htmlentities($e['message']);
}
Code to display records from resultset below:
while (($row = oci_fetch_array($stid,OCI_RETURN_NULLS+OCI_BOTH))==TRUE) {
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "<td>".$row[4]."</td>";
echo "<td>".$row[5]."</td>";
echo "<td>".$row[6]."</td>";
echo "<td>".$row[7]."</td>";
echo "<td>".$row[8]."</td>";
echo "<td>".$row[9]."</td>";
echo "<td>".$row[10]."</td>";
echo "<td>".$row[11]."</td>";
echo "<td>".$row[12]."</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>
Any idea why I don't see anything on the PHP output? Even no errors in the error_log?
Thank you.
in your comment above you said
it doesnt like where clause. PHP pulls data without where clause fine. any idea why OCI8 would cause issue with " WHERE TRADE_DATE=TO_CHAR(SYSDATE, 'DD-MON-YY')"?
well thats because your TRADE_DATE column is a DATE not a VARCHAR
desc IRINS_COMPOSITE_INSTRUMENTS
Name Null Type
------------------- -------- -------------
...
TRADE_DATE DATE
so doing TO_CHAR(SYSDATE, 'DD-MON-YY') creates a STRING which is then converted back to a DATE using your current NLS_DATE_FORMAT setting
assuming you are just trying to ignore the time component of SYSDATE try just changing it to
WHERE TRADE_DATE=TRUNC(SYSDATE)
assuming that fixes it, it has nothing to to with OCI or OCI_FETCH_ARRAY()

Print MySQL table in PHP without knowing the columns

Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.

PHP: Can't Get Oracle Table to Display on Page

This is probably a really obvious error. Anyway, some details:
I have an oracle database that I need to extract data from to populate a table on a PHP page. The table is called Flowers and has Name, Price and Stock columns.
The part of the PHP code I'm having trouble with is this:
$titlevalue = Trim($_REQUEST['search']);
$query = "SELECT * FROM FLOWERS WHERE NAME = '$titlevalue'";
$stmt = OCIParse($connect, $query);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCIExecute($stmt);
The rest of my PHP works -perfectly- when using a different table on my database, which I did as a test. Just in case, this is the code that prints the query results (it's part of an HTML table, but you can ignore that):
while(OCIFetch($stmt)) {
echo "<tr valign=top bgcolor=#F7D4A3>";
$fg1 = OCIResult($stmt,"NAME");
echo "<td width=75>";
echo $fg1;
echo "</td>";
// Display values in column two.
$fg2 = OCIResult($stmt,"PRICE");
echo "<td width=75>";
echo ($fg2);
echo "</td>";
// Display values in column three
$fg3 = OCIResult($stmt, "STOCK");
echo "<td width=75>";
include($fg3);
echo "</td>";
echo "</tr>";
}
No matter what $titlevalue becomes, I just can't get results with this table. I have also tested it with a generic $query = "SELECT * FROM FLOWERS";, but that didn't produce anything either.
Could someone please lend a hand? :( It's been a very long night.
If I may, two things just to note:
1) you're using '$titlevalue', i think that will translate as ... $titlevalue in the query, and not its value
2) Its late ... have you checked that your table is called FLOWERS (case sensitivity)
I'd comment, but I dont have the rep to do so.
If this was helpful, please +1 or click the tickmark. I normally try and use the full format when doing sql queries
SELECT * FROM `table name` WHERE 'x'
... etc. where possible

PHP syntax help on if statement

I'm trying to determine the right syntax from what I'm trying to do with MySQL. I'm basically saying that if a value in a certain column of a row of a table is equal to some session variables, I want to echo out info.
I have a table with subject, description and user. User is set by taking the current user's first name and last name and inserting it into the table under user. This is done by the following code:
$sql="INSERT INTO tbl_name (subject, description, user)
VALUES
('$_POST[subject]','$_POST[description]','$_SESSION[firstname] $_SESSION[lastname]')";
Then once I'm calling this data back out, I want to basically allow the user to delete content that they submitted themselves. The first step for me is to be able to display it in the table. I believe this is just syntax error, but I've confused myself now with how things are set up:
$sql = "SELECT * FROM tbl_name ORDER BY subject, description
LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME EXAMPLES:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if('$field->user' == '$_SESSION[firstname] $_SESSION[lastname]'){
echo '<td>You can delete this</td>';
}
}
I figured the $field->user would equal $_SESSION[firstname] $_SESSION[lastname] because that's how it was initially submitted to the table (without the '.' for concatenation).
Any help would be appreciated. Thanks!
EDIT
Here's the result of my table output code. The results are actually being display with $cell instead of from within the for loop I believe. I've added the if statement in after the but it doesn't seem to recognize echo "<td>".$field->user."</td>"; which makes me think that that is where the problem lies. What I would like to do is be able to add the if statement in a immediately after `echo {$field->user}"; to keep the code clean. I think I've confused myself thoroughly:
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME JOBS:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if($field->user == $_SESSION[firstname]." ".$_SESSION[lastname]){
echo '<td>You can delete this</td>';
}
else{
echo "<td>".$field->user."</td>";
echo "<td>".$_SESSION[firstname]." ".$_SESSION[lastname]."</td>";
}
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no jobs!';
}
I re-wrote the code in a way that was a little bit easier for me to understand (though maybe not the shortest way to do it):
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
It ended up working this way. If there's way to do this shorter then feel free to post it here otherwise thanks for the help!

Categories