Oracle + PHP : Display results in HTML Table - php

I'm having a little trouble tinkering with PHP and Oracle using OCI8 to connect. I've confirmed that i'm able to connect, but keep getting the below error:
PHP Fatal error: Call to a member function query() on resource ... on line 17.
Here's the code I have currently
<?php
$DB = '//DBGOESHERE:PORT/SIDHERE';
$DB_USER = '****';
$DB_PASS = '****';
$conn = oci_connect($DB_USER, $DB_PASS, $DB);
//check for errors
if (!$conn)
{
$e = oci_error();
print htmlentities($e['message']);
exit;
}
$sql = "select display_name, last_export_file, last_export_date from schema.ms_export where last_export_date > sysdate -1 order by last_export_date desc";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'display_name') . " | ";
echo oci_result($stid, 'last_export_file') . " | ";
echo oci_result($stid, 'last_export_date') . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Any help would be greatly appreciated! Technically I'm trying to get it to output into a pretty HTML table, but starting with cheap and dirty line breaks.
Thank you!

Ends up the above was correct and I hadn't synced the most recent version of the php file. Sorry for the trouble!

Related

PHP function within MySQL result

I am very new to PHP. I have been programming in PLSQL and .NET for a while. I have a tricky assignment since I lack PHP experience. n1, n2, n3 are all numeric values identifiers for employees. I want to call a function that looks up the employee by the number and return the employee name on the html page. In PLSQL I would create a function and call it but I am not sure how to do it here.
<?php
$servername = "localhost";
$username = "username ";
$password = "password";
$dbname = "dbname ";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function GetEmployee($nEmployee){
$result = mysql_query("SELECT szLastName FROM employee WHERE nEmployee =
$nEmployee ") or trigger_error(mysql_error());
return $result;
}
$sql = "SELECT idPosition, n1, n2, n3 FROM offense ORDER BY idPosition";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["idPosition"]."</td><td>".$row[$GetEmployee("n1")]."
</td>
<td>".$row[$GetEmployee("n2")]."</td><td>".$row[$GetEmployee("n3")]."</td>
</tr>";
}
} else {
echo "<tr><td>"%nbsp;"</td><td>"%nbsp;"</td><td>"%nbsp;"</td><td>"%nbsp;"
</td>
</tr>";
}
$conn->close();
?>
There are quite a few bugs in there.
You are using both mysql and mysqli ( mysql is deprecated and you should rather use PDO than mysqli, but if you wanna keep it, keep it with mysqli everywhere in your code ).
Instead of $row[$GetEmployee("n1")] you should use $row[GetEmployee("n1")]
Once you change your functions from mysql to mysqli you'll have to pass the connection variable and to access it inside your getemployee function you have to either make it global by declaring global $conn; inside your getemployee function or to pass it as parameter.
After setting those right, you'll probably stil get "Undefined offset: 0" error because you are trying to access an element of the array at a key that doesn't exist in your case.
Here it is fixed, but I might've missunderstood your table structure or expected output since you haven't provided any examples, but I'm confident you'll find what you need in it as it takes the n1, n2, n3 from offense and then pull szLastName for each one of them from employee:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function getEmployee($nEmployee){
//Declare your global conn to be able to use it inside
//the function, HOWEVER, this is not recommendet.
global $conn;
$resultEmployee=mysqli_query($conn, "Select szLastName from employee WHERE nEmployee = $nEmployee");
while($row=mysqli_fetch_assoc($resultEmployee)){
return $row['szLastName'];
}
}
$resultNumbers = mysqli_query($conn, "SELECT idPosition, n1, n2, n3 FROM offense ORDER BY idPosition");
if($resultNumbers ->num_rows > 0){
while($row = mysqli_fetch_assoc($resultNumbers)){
echo "<tr><td>";
echo $row['idPosition'];
echo "</td>";
echo "<td>";
echo getEmployee($row['n1']);
echo "</td>";
echo "<br/>";
echo "<td>";
echo getEmployee($row['n2']);
echo "</td>";
echo "<br/>";
echo "<td>";
echo getEmployee($row['n3']);
echo "</td></tr>";
}
}
$conn->close();
?>
If you are new to PHP and want to continue, you should write your PHP to MySQL connections using PDO. (A very good source is: https://phpdelusions.net/pdo )
Also this is my first answer on StackOverflow, I hope you find it useful.

trouble connecting to dashDB on BlueMix

Here is my code of my .php app connecting to dash-DB instance
//parse VCAP_SERVICES Environment variable
$vcap_services = $_ENV["VCAP_SERVICES"];
$services_json = json_decode($vcap_services,true);
$sqldb = $services_json["dashDB"];
if (empty($sqldb)) {
echo "No sqldb service instance is bound. Please bind a sqldb service instance";
return;
}
//Get Credentials object (db,host,port,username,password)
$sqldb_config = $services_json["dashDB"][0]["credentials"];
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=".
$sqldb_config["db"].
";HOSTNAME=".
$sqldb_config["host"].
";PORT=".
$sqldb_config["port"].
";PROTOCOL=TCPIP;UID=".
$sqldb_config["username"].
";PWD=".
$sqldb_config["password"].
";";
$conn = db2_connect($conn_string, '', ''); //db connection
$sql = "SELECT * FROM BX1_USERS WHERE Username ='$username'";
$foundElements = 0;
if ($conn) {
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
//lLINE 44 that the output.txt fiel referres to starts here
while ($row = db2_fetch_assoc($stmt)) {
$dbusername = $row['Username'];
$dbpassword = $row['Password'];
$dbfirstname = $row['FirstName'];
$dblastname = $row['LastName'];
$foundElements = 1;
}
}
print $foundElements;
echo "<br>";
print $sql;
echo "<br>";
if ($foundElements == 1){
/// rest of my code here
I tested the printed $sql in the database console and it works just fine.. .. but still $foundElements = 0 ...
I get this error in the recent logs file:
"
PHP Warning: db2_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/vcap/app/www/login.php on line 44,
"
I even added this to the code:
print $sqldb_config["db"];
echo "<br>";
print $sqldb_config["host"];
echo "<br>";
print $sqldb_config["port"];
echo "<br>";
print $sqldb_config["username"];
echo "<br>";
print $sqldb_config["password"];
and the page show the same exact values as in my VCAP.
after a few hours of banging my head against the wall I found an answer.
the code I was using was from a connection and queries I used on the IBM SQLDB...
and fro whatever reason I had to change it a little bit to work with IBM dashDB.
I had to change:
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
to
$stmt = db2_exec($conn, $sql);

Extracting values from a database to populate a dropdown

I have a db, am trying to extract values into a list
Here is the code I am trying to run (I had to adapt it from elsewhere), which should return an array, from which I want to select the AllianceName attribute
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($dbname, $con);
$options = array();
$options[] = "<option value=''>--?--</option>";
$query = "
SELECT *
FROM `City`
GROUP BY `AllianceName`
";
$db = mysqli_query($query);
foreach ( $db as $d ) {
$options[] = "<option value='{".$d['AllianceName']."}'></option>";
}
?>
<select class="" id="articles" size="1" name="articles">
<?php echo implode("\n", $options); ?>
</select>*/
Right now this only returns the --?-- that I have defined in the options array. It does not parse any of the values from the query. I know the query by itself is correct since I have run it exactly in this syntax in the SQL server and it works.
I am pretty sure that this is a syntax error ... var_dump($db) gives me a bool(false) output.
Here's the latest code I am using:
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
<select class="Select" id="articles" size="1" name="articles">
<?php
$sql = <<<SQL
SELECT DISTINCT `AllianceName`
FROM `City`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo "<option value="'.{$row['AllianceName']}.'"></option>";
}
?>
</select>
The query by itself runs fine when I just echo the results. Trying to put it into a dropdown fails every time. No values get populated.
There are a couple problems here.
First you don't need the GROUP BY 'AllianceName' in your query, you are not performing any functions on your data, that might have been causing you to not return any results.
Secondly, normally you loop through query results with a while loop. You don't have to, but its common practice, so your code should look like this..
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//there is no need to make an array first, just have it spit out the options if you aren't making a class or function
?>
<select class="" id="articles" size="1" name="articles">
<?php
$query = "SELECT * FROM `City` ";
$db = mysqli_query($query);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['AllianceName']."}'></option>";
}
?>
</select>
Try that out and see if it works for you.
From the mysqli_query() docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
So what you have after the query succeeded is a mysqli_result object. Now you have to fetch the result into an (associative) array or object, row by row.
if($query === false) die('Query failed to execute');
while($row = $result->fetch_assoc()) {
echo $row['AllianceName'] . PHP_EOL;
}
All this is described in hundreds of tutorials in the web, so please read one of these. I recommend these written in the current decade, e.g. http://codular.com/php-mysqli
Here is the code that finally worked. Both #Syndrose and #Zombiehunter provided clues to this.
#Syndrose - you might want to take into account the syntax used here as this is what was failing from your codebase...especially the syntax for the echo tag line.
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL
SELECT DISTINCT `AllianceName`
FROM `City`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
?>
<select style="width:300px" class="" id="AllianceName" size="1" name="Alliance Name">
<?php
while($row = $result->fetch_assoc()){
echo '<option value='.$row['AllianceName'].'>'.$row['AllianceName'].'</option>';
}
?>
</select>

PHP not displaying MYSQL result

I created a script on a windows platform which connects to the mysql database and returns the results of a table. A very basic script which I wrote to simply test my connection worked. The script works fine on my windows machine but not on my new mac. On the mac it simply does not display any records at all.
I know that the database connection has been established because there is no error but I can not see why the result set is not being displayed on screen, as I said it worked fine on my windows machine.
The Mac has mysql (with data) and apache running for php.
Please could someone help as I have no idea what to do now?
Script below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'test';
mysql_select_db($dbname);
mysql_select_db("test", $conn);
$result = mysql_query("SELECT * FROM new_table");
while($row = mysql_fetch_array($result))
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
mysql_close($con);
There are various things you could do to debug this.
Show all PHP errors.
ini_set('display_errors','On');
ini_set('error_reporting',E_ALL);
Catch all possible MySQL errors, not only the ones concerning whether you connected successfully.
mysql_select_db("test", $conn) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
Side note: There's no reason to select which database you wish to use twice.
Its very difficult to see what is wrong ... so add some basic error checking, like changing this
$result = mysql_query("SELECT * FROM new_table");
to
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
This will show you the error you are getting from your query (if there is one) .. you ill see in the documentation for mysql_query that it returns a boolean if there was an error
Also note that you have a mistake in the variable name for closing the MySQL Connection :
mysql_close($con);
should be
mysql_close($conn);
Check to see if the SELECT query was successful or not before fetching the rows.
<?php
$result = mysql_query("SELECT * FROM new_table");
if(!$result)
die('SQL query failed: ' . mysql_error());
The only thing i can think of is that Mac file system is case sensitive while windows isn't so it might be that you mispelled the name of the table. In any cas you should do
$result = mysql_query("SELECT * FROM new_table") or die("error:".mysql_error());
to view the error
I think you should use the improved PHP mysql driver
try
{
$db = new mysqli("localhost","root","root","test");
if ($db->connect_errno) {
throw new Exception($db->connect_error);
}
if ($result = $db->query("SELECT * FROM new_table")) {
printf("Select returned %d rows.\n", $result->num_rows);
while($row = $result->fetchAssoc())
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
/* free result set */
$result->close();
}
$db->close();
}
catch(Exception $e)
{
printf("Database Error: %s\n", $e->getMessage());
exit();
}

Pass a PHP variable to a MySQL query

What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.

Categories