I am trying to connect to Oracle database from the following PHP script to populate a drop down list but the script doesn't work.
Can anyone see an issue? Many thanks!
$conn = oci_connect('username', 'password', 'host');
$stid = oci_parse($conn, 'select product_id, product_name from product order by product_id');
oci_execute($stid);
$query = "select product_id, product_name from product order by product_id";
$res = mysql_query($stid);
echo "<select name = 'Product'>";
while (($row = mysql_fetch_row($res)) != null)
{
echo "<option value = '{$row['product_id']}'";
if ($selected_product_id == $row['product_id'])
echo "selected = 'selected'";
echo ">{$row['product_name']}</option>";
}
echo "";
Why are you using mysql_* to interrogate an oracle database?? I think the right function to use is oci_execute
$res = mysql_query($stid);
The above line in your code is used to query a MySQL database,not Oracle.
Related
I've been trying to make my php code to show entries from my mysql database. I wanted to make it automatic in a sense that i wouldn't need to print the tables manually instead they would be printed according to an alogrythm, but it doesn't work like intended.
I've tried different ways of setting up the table but none of them worked, the furthest I got was to print one entry from the table, and spitting errors after it.
$base = $_POST["base"];
$connection = mysqli_connect("localhost","login","pass") or die("Impossible to connect to the database!");
$db = mysqli_select_db($connection, "database")or die("Impossible to download the database!");
$sql = "SELECT * FROM $base";
$mysqli_result = mysqli_query($connection, $sql);
$sql2 = "SHOW COLUMNS FROM $base";
$set1 = mysqli_query($connection, $sql2);
$colu = array();
while($db = mysqli_fetch_row($set1)){
$colu[] = $db[0]; }
$columns=implode("<br/>",$colu);
echo "<TABLE BORDER=1>";
echo "<TR><TH>$colu[0]</TH><TH>$colu[1]</TH><TH>$colu[2]</TH><TH>$colu[3]</TH><TH>$colu[4]</TH><TH>$colu[5]</TH></TR>";
while ($row = mysqli_fetch_array($set1)) {
$colu[0] = $row["echo $colu[0]"];
$colu[1] = $row["echo $colu[1]"];
$colu[2] = $row["echo $colu[2]"];
$colu[3] = $row["echo $colu[3]"];
$colu[4] = $row["echo $colu[4]"];
$colu[5] = $row["echo $colu[5]"];
echo "<TR><TD>$colu[0]</TD><TD>$colu[1]</TD><TD>$colu[2]</TD><TD>$colu[3]</TD><TD>$colu[4]</TD><TD>$colu[5]</TD></TR>";}
echo "</TABLE>";
mysqli_free_result($mysqli_result);
mysqli_close($connection); ?>
the $_POST[$base]; part works, Im guessing the issue is in the while loop as it doesnt complete once, and I'm lost as to why it doesnt want to work.
I see some problems in you script. If you want to fetch columns as heading and the content for the table body you are using the wrong result sets.
// next line make it possible to do sql insertion, and what if $base has no input?
$base = $_POST["base"];
// the die will never be reached
$connection = mysqli_connect("localhost","login","pass") or die("Impossible to connect to the database!");
$db = mysqli_select_db($connection, "database")or die("Impossible to download the database!");
// where is this query for?
$sql = "SELECT * FROM $base";
// where is this result being used
$mysqli_result = mysqli_query($connection, $sql);
$sql2 = "SHOW COLUMNS FROM $base";
$set1 = mysqli_query($connection, $sql2);
$colu = [];
// what if the table order chages? Best to use mysqli_fetch_assoc
while($db = mysqli_fetch_row($set1)){
$colu[] = $db[0];
}
// where do you use $comumns?
$columns = implode("<br/>", $colu);
echo "<TABLE BORDER=1>";
echo "<TR><TH>$colu[0]</TH><TH>$colu[1]</TH><TH>$colu[2]</TH><TH>$colu[3]</TH><TH>$colu[4]</TH><TH>$colu[5]</TH></TR>";
// you already fetched all record from set1
while ($row = mysqli_fetch_array($set1)) {
$colu[0] = $row["echo $colu[0]"];
$colu[1] = $row["echo $colu[1]"];
$colu[2] = $row["echo $colu[2]"];
$colu[3] = $row["echo $colu[3]"];
$colu[4] = $row["echo $colu[4]"];
$colu[5] = $row["echo $colu[5]"];
echo "<TR><TD>$colu[0]</TD><TD>$colu[1]</TD><TD>$colu[2]</TD><TD>$colu[3]</TD><TD>$colu[4]</TD><TD>$colu[5]</TD></TR>";
}
echo "</TABLE>";
mysqli_free_result($mysqli_result);
mysqli_close($connection); ?>
This biggest issue you have right now is this:
$base = $_POST["base"]
$sql = "SELECT * FROM $base";
$sql2 = "SHOW COLUMNS FROM $base";
This is a huge SQL Injection vulnerability, even if they pass just an empty string to this it's all bad. For example that would result in a query error and depending on your settings on the server and for error reporting, you may expose quite a bit of info. Just one example is a stack trace could contain DB passwords etc.
Instead of directly using user input make a whitelist like this:
$tables = ['user', 'user_meta', 'states']; //etc
$base = !empty($_POST["base"]) && false !== ($index = array_search($_POST["base"], $tables)) ? $tables[$index] : false;
if(!$base) die('Unknown table '.$_POST["base"]);
This way you are only using data you know the value of.
Variable reuse
Other then that, your variable names are causing a bunch of "code confusion". This is what happens if you have to generic of a variable name. Some examples:
$db = mysqli_select_db(...)
while($db = mysqli_fetch_row($set1)){ //overwriting db
...
}
//....................
while ($row = mysqli_fetch_array($set1)) {
$colu[0] = $row["echo $colu[0]"]; //overwriting $colu
This last one is also wrong because the row key will be something like:
$colu[0] = $row["echo name"];
Or something with a column name. Because you are re-using this variable ("variable confusion" ) on the next loop it will be the value of $row["echo $colu[0]"]; which will get put back into that. So lets assume this is correct without the echo and will use Name as the value.
//loop 1
$colu[0] = 'name';
$row['name'] = 'Tom';
//result
$colu[0] = 'Tom'
//loop 2
$colu[0] = 'Tom';
$row['Tom'] doesn't exist.
//result
$colu[0] = null; //undefined index warning
Cursor Reuse
You are also reusing the DB cursor $set1 and looping over it 2 times. I'm not sure about MySqli, but PDO won't allow you to do that. This is probably why the second loop is failing. I believe the second one should be $mysqli_result. It's a bit confusing because you do both queries then loop though one then the other. Instead of doing a query, looping through it. Then doing the other, and looping though that.
Instead you can do something like this:
//you can even query the DB for the table names
$tables = ['user', 'user_meta', 'states']; //etc
$base = !empty($_POST["base"]) && false !== ($index = array_search($_POST["base"], $tables)) ? $tables[$index] : false;
if(!$base) die('Unknown table '.$_POST["base"]);
$connection = mysqli_connect("localhost","login","pass") or die("Impossible to connect to the database!");
$db = mysqli_select_db($connection, "database")or die("Impossible to download the database!");
//---------query for the columns
$sql = "SHOW COLUMNS FROM `$base`";
$mysqli_result = mysqli_query($connection, $sql);
$columns = [];
while($row = mysqli_fetch_row($mysqli_result)){
$columns[] = $row[0];
}
//---------query for the data
//use the column result in the select part of query, because the column names
//come from the DB they are safe to use.
$sql = "SELECT `".implode('`,`', $columns)."` FROM `$base`"; //reuse sql (no longer needed)
$mysqli_result = mysqli_query($connection, $sql); //reuse results (no longer needed)
//fetch all data as assoc array. because we tied it to the results
//of the first query, the column names. We no longer need to map it.
$data = mysqli_fetch_all($mysqli_result, MYSQLI_ASSOC);
///output table and headers
echo "<table>";
echo "<thead>";
echo "<tr>";
//we can just loop over the columns and put them in the table head
foreach($columns as $key ){
echo "<th>$key</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
//loop over each row of data
foreach($data as $row){
echo "<tr>";
//loop over each "correlated" column
foreach($columns as $key ){
echo "<td>{$row[$key]}</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
BONUS For getting the table names from the DB:
$sql = 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE "'.$database.'"';
$mysqli_result = mysqli_query($connection, $sql);
$tables = mysqli_fetch_all($mysqli_result, MYSQLI_NUM);
Hope that makes sense.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I tried inserting this into my code to generate a dropdown menu through an sql table but it responds with nothing in the dropdown. When I execute the sql query it doesn't show any error as well. Please be kind enough to fix my error. Thank you
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
mysqli_query($db, $sql);
echo "<select name='unitid'>";
while ($row = mysql_fetch_array($sql)) {
echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
}
echo "</select>";
?>
Try saving the result of mysqli_query:
$result = mysqli_query($db, $sql);
And then using it in the while condition:
while ($row = mysqli_fetch_array($result)) {
The select should be also "Select unitid, unitname ..." to return also the unitname used in the options:
$sql = "SELECT unitid, unitname FROM unit WHERE unitname = '$unitname'";
And you should use prepared statements if you want to prevent it from SQL injection attacks.
If you want all the units to be shown on the combo change the select to:
$sql = "SELECT unitid, unitname FROM unit";
So, the code should be now:
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "Select unitid, unitname from unit";
$result = mysqli_query($db, $sql);
echo "<select name='unitid'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
}
echo "</select>";
?>
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "Select unitid, unitname from unit where unitname=\"".$unitname."\"";
$rows = array();
$return = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($return, MYSQLI_ASSOC))
$rows [] = $row;
echo "<select name='unitid'>";
for($i=0; $i<count($rows); $i++)
echo "<option value='".$rows['unitid']."'> ".$rows['unitname']."</option>";
echo "</select>";
?>
you didn't fetch the array correctly, so your query basically returned an empty array. You also wrote a wrong query. This solution should work fine
I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php
In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!
I have connected a oracle database with PHP. When I try to query a data in sqlplus it works. But when I try to query in PHP, it doesn't work(It doesn't show any error or nothing). My emp_id is number.
<p> $query = "select order_id from ordered_by where order_emp_id =".$emp_id."and order_done='N'";
$stid = oci_parse($conn, $query);
$r = oci_execute($stid, OCI_DEFAULT);
$value="";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
foreach ($row as $item)
{
$item!== null ? htmlentities($item) :'NULL';
$value =$item;
}
Put a space after =".$emp_id."
$query = "select order_id from ordered_by where order_emp_id =".$emp_id." and order_done='N'";