How to fix conflict in foreach mysql PDO
I Try use other looping function but no give result, like while.this my script
the mysql PDO query, like this:
<?php
function calldata($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
while($res = $q->fetch(PDO::FETCH_ASSOC)){
$record = array_map('stripslashes', $res);
$db->records[] = $record;
}
return $db->records;;
//else echo "No records found";
}
?>
and to display the result, like this:
<table>
<tr><td>Category</td><td>
<select>
<option value="0">- select -</option>
<?php
try{
$db = dbConn::getConnection();
$table='str_prod_category';
$recordscat = calldata($table);
if(count($recordscat)){
foreach($recordscat as $key1=>$Recordcat){
?>
<option value="<?=$Recordcat['id_category'];?>"><?=$Recordcat['cat_name'];?></option>
<?php }}}catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error " . $e->getMessage();
} ?>
</select>
</td></tr>
<tr><td>Brand</td><td>
<select>
<option value="0">- Select -</option>
<?php try{
$db = dbConn::getConnection();
$table1='str_prod_brand';
$recordsbrand = calldata($table1);
if(count($recordsbrand)){
foreach($recordsbrand as $key2=>$Recordbrand){
?>
<option value="<?=$Recordbrand['id_brand'];?>"><?=$Recordbrand['brand_name'];?></option>
<?php }}}catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error " . $e->getMessage();
} ?>
</select>
</td></tr>
</table>
this code is work and dislpay the data but for the option select brand, There is an empty selection, and then the right data after the empty data.
how to fix this?i have tried change the loop from foreach to while but no give result.
thanks
i try to use fillter using if and it's work to remove the blank recode
foreach($recordsbrand as $key2=>$Recordbrand){
if($Recordbrand['brand_name'] == ''){}else{
<option value="<?=$Recordbrand['id_brand'];?>"><?=$Recordbrand['brand_name'];?></option>
}}
but, i don't know is good or bad.
Related
I am trying to displays value of selects options dynamically in PHP. Basically user creates those options awhich are stored in database and then I am trying to fetch this at different place. for this purpose i wrote the below function:
function fetch_acad_yr($conn) {
$query = "SELECT a.fk_acadyear_id as acadyearid,b.acad_year as acadyear FROM tbl_admparam a inner join list_acad_years b on a.fk_acadyear_id = b.pk_acad_year_id";
$stmt = $conn->prepare($query);
if ($stmt->execute()) {
foreach ($stmt as $row) {
?>
<option value="<?php echo $row['acadyearid'] ?>"><?php echo $row['acadyear'] ?></option>
<?php
}
}
}
then in html i called this function
<select class="form-control" id="acad_period" name="acad_period" required>
<option value="">Please select...</option>
<?php fetch_acad_yr($conn); ?>
</select>
But the options doent show any values it simply come blank and is not dispalying the values stored in database. I tried running the query separately and the query is returning the desired result
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$con = new mysqli($servername, $username, $password,$dbname);
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
?>
<select name="acad_period" required="">
<option value="0">Select</option>
<?php
$s= "SELECT a.fk_acadyear_id as acadyearid,b.acad_year as acadyear FROM tbl_admparam a inner join list_acad_years b on a.fk_acadyear_id = b.pk_acad_year_id";
$ex= $con->query($s);
if (!$ex)
{
echo("Error description: " . mysqli_error($con));
}
else
{
while ($f= $ex->fetch_assoc())
{
?>
<option value="<?php echo $f['acadyearid'] ?>"><?php echo $f['acadyear'] ?></option>
<?php
# code...
}
}
?>
</select>
Make sure you have the right connection and the data coming in the query result.
Basic php mysql code I used was the below and it worked. You make change it to pdo or propel and get the result. But the usage is same with while or for loop.
$conn = mysql_connect($host, $username, $pass);
mysql_select_db($dbname, $conn);
echo "<pre>";
echo "<select>";
fetch_acad_yr($conn);
echo "<\select>";
function fetch_acad_yr($conn) {
$query = "SELECT a.fk_acadyear_id as acadyearid,b.acad_year as acadyear FROM tbl_admparam a inner join list_acad_years b on a.fk_acadyear_id = b.pk_acad_year_id";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res)){
?>
<option value="<?php echo $row['acadyearid'] ?>"><?php echo $row['acadyear'] ?></option>
<?php
}
}
?>
Works for me.
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
WTF? - this is becoming a nightmare, just seem to get error after error.. Im willing to pay someone for their time just to help me achieve what seems to be the unachievable, please.. alls I want is a dropdown menu that selects data from a table according to its category and displays it.. HELP! :(
<form action="portfolio.php" method="post">
<select onload="displayProject(this.value);" onchange="displayProject(this.value);">
<option value='none'>All</option>
<option value='1'>Fencing</option>
<option value='2'>Driveway</option>
</select>
</form>
<?php
$db = new mysqli('localhost', 'wlarter_user', 'pw', 'wlarter_portfolio');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$option= $_POST['option'];
$queries = "SELECT * FROM image";
if ($option != 'none'){
$queries = "SELECT * FROM image where category=".$option;
}
$result=#mysqli_query($db,"$queries");
while($row = mysqli_fetch_array($result))
{
?>
<div class="box-portfolio"> <?php echo $row['Img']; ?> </div>
<?php
}
mysqli_close($db);
?>
Simply turn it around, is probably what you want:
$queries=$query;
into
$query = $queries;
FULL code:
<FORM action="portfolio.php" method="post">
<SELECT onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='none'>All</OPTION>
<OPTION VALUE='1'>Fencing</OPTION>
<OPTION VALUE='2'>Driveway</OPTION>
</SELECT>
</FORM>
<?php
$db = new mysqli('localhost', 'wlarter_user', 'pw', 'wlarter_portfolio');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$option= $_POST['option'];
$queries = "SELECT * FROM image";
if ($option != 'none'){
$queries = "SELECT * FROM image where category=".$option;
}
$query=$queries;
$result=mysqli_query($db,"$query");
while($row = mysqli_fetch_array($result))
{
?>
<div class="box-portfolio"> <?php echo $row['Img']; ?> </div>
<?php
}
mysqli_close($db);
?>
can you try like this.......
$result=#mysqli_query($db,"$queries");
replace this line
$result=#mysqli_query($db,"$queries");
with this:
$result=#mysqli_query($db,$queries);
it may help..
Because the result of a mysql query can be a resource or a boolean value (if it failed), you should check the result of your query like this after executing it:
if ($result !== false) {
while($row = mysqli_fetch_array($result))
{
?>
<div class="box-portfolio"> <?php echo $row['Img']; ?> </div>
<?php
}
}
else {
// do your error message stuff here
echo mysqli_error($db);
}
Im trying to load data from the database dynamically. Like when user click on select button in a form, the data will be loaded dynamically from the database. But the problem is I have to use PDO. Im not getting the output, don't know what's wrong. Here is my code-
<tr><td><font size="+1">Region :</font></td>
<td><Select name="region" class="regionfields" id="wineRegion">
<option id="0">-- Select Region --</option>
<?php
$hostname = 'localhost';
$username = 'ovic';
$password = 'root';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=winestore", $username, $password);
echo 'Connected to database<br />';
$sql = "SELECT region_name FROM region";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
foreach($obj->region_name AS $W)
{?>
<option id="<?php echo $W; ?>"><?php echo $W; ?></option>
<?php
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</Select></td></tr>
You may need to use $stmt->fetchAll() which returns an array of objects. The fetch() method returns only a single object.
$regions = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($regions as $region) {
?>
<option id="<?php echo $region->region_name; ?>">
<?php echo $region->region_name; ?></option>
<?php
}
If that fails, trying doing a print_r on the result of fetchAll() to see if you are getting anything back.
To begin with, I'm having this small PDO snippet of code which gets me all available databases on the server and another function for the tables:
I need whenever I select and submit an option from the db list to display its corresponding tables in the select menu below. I managed to display the databases with a foreach but I kinda miss the point why this doesn't work.
Thanks in advance for any answers/solutions :)
see below for a revision to your code in order to achieve what you're looking for.
<form method='post' action="<?php $_SERVER['PHP_SELF']; ?>">
<?php
define('PDO_USER', 'root');
define('PDO_PASS', '');
function getDatabases(PDO $pdo) {
$stmt = $pdo->query('SHOW DATABASES');
$result = $stmt->fetchAll();
$dbs = array();
foreach($result as $row) {
$dbs[] = $row['Database'];
}
return $dbs;
}
$pdo = new PDO('mysql:host=localhost', PDO_USER, PDO_PASS);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$databases = getDatabases($pdo);
// Table code
$selectedDB = (!empty($_POST['database'])) ? $_POST['database'] : null;
function getTables(PDO $pdo, $databaseName) {
if(!in_array($databaseName, getDatabases($pdo))) {
return array();
}
$stmt = $pdo->query('SHOW TABLES FROM '.$databaseName);
$result = $stmt->fetchAll();
$tables = array();
foreach($result as $row) {
$tables[] = $row['Tables_in_'.$databaseName];
}
return $tables;
}
$tables = array();
if(!empty($selectedDB)) {
$tables = getTables($pdo, $selectedDB);
}
?>
Database:
<select name='database'>
<?php foreach($databases as $row): ?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<?php endforeach; ?>
</select>
<input type='submit' name='formSubmit' value='Submit'></form>
UPDATE
<select name='formTable1'>
<?php foreach($tables as $tbName): ?>
<option value='<?php echo $tbName; ?>'><?php echo $tbName; ?></option>
<?php endforeach; ?>
</select>
A couple of notes:
You need to include the "action" attribute in the form tag in order to give the form a target URL for submission.
In your original select you had 2 name attributes
(name='formDatabases[]' name='database'). You should only have one
name per form element, which is what is determined to be used as the
key in the $_POST array for that particular field.
You should only use "name='var[]'" format in the HTML, if you expect
that particular POST item to be an array in PHP. Otherwise you can
just use "name='var'"
This may be out of the scope of your original question, but you may
want to consider separating your database business logic into a separate
class, to keep your HTML clean. For now at least, I updated the code to have
the logic at the top of the file so that in can be extracted into a
class more easily in the future. This avoids the perilous path into PHP Spaghetti string code!
I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the table2 where the column id = 340 and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the users which updates the new values to the table1 with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
For example lets say I have 3 fruits in the table and I select pear it updates the table with a "1" instead of the word "pear"
apple
pear
peach
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Slot1 : <select name="slot1">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM table2 where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$slot1 = 0;
foreach($rowarray as $row)
{
echo "<option value = $slot1 >$row[FirstName] $row[LastName]</option>";
$slot1++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE table1 SET Slot1place = :slot1 WHERE ID = '340'");
$stmt->bindParam(':slot1', $slot1,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
You dont use sqlite_escape_string if youre using a prepared statement like that. The values are going to be quoted witn they are bound to the statement.
I think you should check your html syntax (Is it missing tags, and the ).
Check it out at: http://www.w3schools.com/html5/tag_option.asp
echo "<option name = $name >$row[FirstName] $row[LastName]</option>";
Everything else is the right syntax