Populate drop down using PHP ODBC function - php

Can you help me tracing my problem on populating drop down menu using ODBC Function in PHP. Here's my code:
$conn = $conn = odbc_connect("mm370lib", "ictapps", "s3cur3344");
if(! $conn){
print( "Cannot connect to database" );
exit;
}
$qry1 = "SELECT * FROM APSUPP";
//$res = odbc_do($conn, $qry);
$res1 = odbc_exec($conn, $qry1);
echo "<select class='form-control' name='vendor_name'>";
while($row1 = odbc_fetch_row($res1)){
echo "<option value='".$row1["ASNUM"]."'>".$row1["ASNAME"]."</option>";
}
odbc_free_result($res1);
echo "</select>";
It is not showing the fetch data from database.
See attached file

According to the doc, odbc_fetch_row() does not return a row, but just true or false, indicating if a row was fetched. See here for more information: http://php.net/manual/en/function.odbc-fetch-row.php
So, following the doc, you need to call odbc_result() after you've fetched a row. See here for more info: http://php.net/manual/en/function.odbc-result.php
It should probably be something like this (I do not have a php environment here right now, so this code is untested):
while(odbc_fetch_row($res1))
{
$asnum = odbc_result($res1, "ASNUM");
$asname = odbc_result($res1, "ASNAME");
echo "<option value='".$asnum."'>".$asname."</option>";
}

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

Printing Query Issue - MySQL, PHP, HTML -

I had a very random problem in an IIS class, it has stumped my tutor so here I am and I'll try my best to explain it well!
I'm running Xampp with Apache and MySQL, I run the query I want and get the expected output to a table, but I have a problem with the outputting of pictures. I have the right file type, extention and path selected, because I can get pictures to show up, but as long as at least one picture in the query result has the extension removed, and this picture will not load.
Database
Website
If I have each query result with the correct name and extension, which is the same as when it shows up, none of them show up at all!
PHP:
<?php
// set server access variables
include 'db2.inc';
// open connection
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databaseName) or die ("Unable to select database!");
// create query
//$query = "SELECT * FROM products";
$query = "SELECT * FROM products WHERE CategoryName = 'Surfboards'";
//Check initial letter
//if (!$initialLetter=="")
//{
// $query = $query." Where country like '$initialLetter%' ";
//}
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=20 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ProductID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Description']."</td>";
echo "<td>".$row['Brand']."</td>";
echo "<td>".$row['Model']."</td>";
echo "<td>".$row['BoardLength']."</td>";
echo "<td>".$row['BoardType']."</td>";
echo "<td>".$row['Colour']."</td>";
echo "<td>"."<img src=images/".$row['Image']."> </td>";
echo "<td>".$row['UnitPrice']."</td>";
echo "<td>".$row['CategoryName']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
Any help or direction would be greatly appreciated!
Thanks
Will
On this line:
echo "<td>"."<img src=images/".$row['Image']."> </td>";
Your image src is not enclosed in quotes. If this is a direct copy/paste of your code then that is definitely a problem, but may not be the only one.
As other people have said, look at pdo, or mysqli. The mysql_ functions you are using are deprecated for multiple reasons.

Creating a drop down list but the php won't work [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 6 years ago.
So there's a lot of people helping to create a drop down list in html and populating it with their database. I'm trying to do this and I found some php code to do it but it just doesn't work. I understand php, sql and html but just not how they combine together. What seems to be the problem is that after the first echo, the rest of the code is just outputted as code to the page and it doesn't do anything. This is the code:
<html>
<body>
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('FoodMatching');
$sql = "SELECT IngID, IngName FROM Ingredient Characteristics";
$result = mysql_query($sql);
echo "<select name='Ingredient Name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['IngName'] ."'>" . $row['IngName'] ."</option>";
}
echo "</select>";
?>
</body>
</html>
And what I see on the webpage is:
"; while ($row = mysql_fetch_array($result)) { echo "
" . $row['IngName'] ."
"; } echo ""; ?>
There's no errors/warnings that pop up so I don't know what the problem is. Thank you if you can help :)
As mentioned you should look to use PDO's to talk to the DB.
If you get the list before the html is output then you can have much cleaner and easier to understand code
See if the below makes sense, you might need to make a few modifications as its untested.
There are some comments about your mySql, ensure that results are being returned when you run the query.
<?php
define( "DB_DSN", "mysql:host=localhost;dbname=foo");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "password" );
// define the empty array to be filled from db
$aIngredeintCats = array();
// any other php tasks that dont needthe ingcats
// store sql
$sSQL = "SELECT IngID, IngName FROM IngredientCharacterisitics";
// create an instance of the connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// prepare
$st = $conn->prepare( $sSQL );
// if required securely bind any user input in the query
// $st->bindValue(":IngID", $sIngName, PDO::PARAM_STR);
// execute the connection
$st->execute();
/* this will show if a result has been returned from the db.
echo "<pre>";
var_dump($st->fetch());
echo "</pre>";
*/
// while myslq has rows loop over them and store
while($row = $st->fetch() ){
// use the IngID from db as the array key
// also strip any tags from the output. other sanatisation should be done
$aIngredeintCats[$row['IngID']] = strip_tags($row['IngName']);
}
// any other php tasks if they need the list of cats
?>
<html>
<body>
<form method='post' action='/'>
<?php
// if there are results stored create the select and loop over
if(!empty($aIngredeintCats)){
echo "<select name='IngredientName'>";
echo "<option value='' default>default</option>"
foreach ($aIngredeintCats as $iIngID => $sIngName) {
echo "<option value='".$sIngName."' >".$sIngName."</option>";
}
echo "</select>";
}else{
echo "<p>No results avaliable!</p>";
}
?>
</form>
</body>
</html>

No data displayed from DB in drop down menu

Echo 'Hello programmers' ;
I'm scratching my head about a pair of drop down menus. They are supposed to display all strings from the ename and mid rows. However this isn't happening and the drop down is only displaying one result from each row. There are multiple strings of test data in the actual rows.
I have some code here and perhaps you could lend a hand. Let me explain.
First off these are the methods from class dbme. To keep the clutter down the second function is exactly the same, except the SQL query for getResult() is obviously different (SELECT * from member as opposed to memberevent)
function openDB() {//creating database connection
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
Second, this is the web-side data.
$db1 = new dbme();
$db1->openDB();
$sql="select mid from member";
$result=$db1->getResult($sql);// get the ids from the tables for the select
$sql1="select ename from event";
$result1=$db1->getResult($sql1);// get the ids from the tables for the select
if (!$_POST) //page loads for the first time
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" onsubmit="return validateForm( );">
Select Member ID: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<br />
Select Event name : <select name="ename">
<?php
while($row = mysqli_fetch_assoc($result1))
echo "<option value='{$row['ename']}'>{$row['ename']} </option>";
?>
</select>
<br />
I have a sneaking suspicion that a variable is getting over written, OR an extra loop is needed somewhere. But I'm not really sure, thus I post this question for advice.
Thanks.
You need to iterate through your results inside your getResults() function, otherwise you will always only get one row.
You are passing in the SQL but never using it:
Change
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
To
function getResult($sql){
$result = mysqli_query($this->conn , $sql );

MySQL retrieval from database not retrieving multiple rows

I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php

Categories