How to save a select option loaded from database in PHP - php

[sample][1]
Good day,
I successfully fetched the values from the database **(db) for the select option using mysqli
but
the problem is whenever I try save it in the database it doesn't retrieve the value selected in select the option .
Can you please give any suggestions on how to deal with this.
<?php
$conn = new mysqli('localhost', 'root', '', 'db') ;
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
} else {
echo"db_connection.php RUNNING<br>";
}
/* CONNECTION IN DATABASE*/
/* WHILE LOOP FOR SELECT OPTION IN DATABASE*/
$result = $conn->query("select b_fname from tbl_client");
echo "<html>";
echo "<body>";
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($b_id, $b_fname);
$b_id = $row['b_id'];
$b_fname = $row['b_fname'];
echo '<form action ="dropdown_demo.php" method="POST" enctype="multipart/form-data" >';
echo '<option name="b_fname" value="/'.$b_fname.'/">'.$b_fname.'.'.$b_fname.'</option>';
echo " </form>";
}
echo '</select><input type="submit" name="add_drop" />';
echo "</body>";
echo "</html>";
/* SQL INSERT THE VALUE TO THE */
$sql = "INSERT INTO tbl_client (b_fname)VALUES ( '$b_fname' )";
if (mysqli_query($conn, $sql)) {
echo('<script>alert("Record Added Successfully!");</script>');
// header('Refresh: 1; URL= import_addnew-Copy.php');
error_reporting(0);
} else {
error_reporting(0);
}
mysqli_close($conn);
?>

I have made some changes in your code. pu the tag out side while loop etc...
Try the below code:
$conn = new mysqli('localhost', 'root', '', 'db') ;
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else
{
echo"db_connection.php RUNNING<br>";
}
/* CONNECTION IN DATABASE*/
/* WHILE LOOP FOR SELECT OPTION IN DATABASE*/
$result = $conn->query("select b_fname from tbl_client");
echo "<html>";
echo "<body>";
echo '<form action ="dropdown_demo.php" method="POST" enctype="multipart/form-data" >';
echo '<select name="b_fname" >';
while ($row = $result->fetch_assoc()) {
unset($b_id, $b_fname);
$b_id = $row['b_id'];
$b_fname = $row['b_fname'];
echo '<option value="'.$b_fname.'">'.$b_fname.'.'.$b_fname.'</option>';
}
echo '</select><input type="submit" name="add_drop" />';
echo " </form>";
echo "</body>";
echo "</html>";
/* SQL INSERT THE VALUE TO THE */
if(isset($_POST['add_drop'])){
$b_fname = $_POST["b_fname"];
$sql = "INSERT INTO tbl_client (b_fname) VALUES ( '".$b_fname."' )";
if (mysqli_query($conn, $sql)) {
echo('<script>alert("Record Added Successfully!");</script>');
// header('Refresh: 1; URL= import_addnew-Copy.php');
error_reporting(0);
} else {
error_reporting(0);
}
}
mysqli_close($conn);

Related

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

I am not getting the result properly when conneting to MySQL

For the code below added, i am not getting any result printed.
$con = #mysqli_connect("localhost","root","","temp");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT * FROM `login`";
echo $query;
$result=#mysqli_query($query) or die(mysql_error());
while($row=mysqli_fetch_array($result))
{
echo $row["username"];
}
Try the below code it will work
//conection:
$con = mysqli_connect("localhost","root","","temp") or die("Error " . mysqli_error($con));
//consultation:
$query = "SELECT * FROM login" or die("Error in the consult.." . mysqli_error($con));
//execute the query.
$result = $con->query($query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["username"] . "<br>";
}
Use this code as it is.
$con=mysqli_connect("localhost","root","","temp");
$result = mysqli_query($con,"SELECT * FROM login");
while($row = mysqli_fetch_array($result))
{
echo $row["username"];
}
// use this code and plz check your db name
$host='localhost';
$user='root';
$pass='';
$db_name='temp';
$con=mysqli_connect($host,$user,$pass,$db_name);
if($con)
{
echo "db connect succecssfully";
}
$slt="select * from login";
$query=mysqli_query($slt,$con);
while($row=mysqli_fetch_array($query))
{
echo $row["username"];
}
<?php
$con=mysqli_connect("localhost","root","","temp");
// Here localhost is host name, root is username, password is empty and temp is database name.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con,"SELECT * FROM login");
while($row = mysqli_fetch_array($result)) {
echo $row["username"] . "<br>";
}
mysqli_close($con);
?>
Use this. it may solve your problem.
//connection
$con = mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

Search Using PHP displays all Database Data

I am trying to search some data from a database. The search works fine, however if I click on search without entering anything into the form, it displays all the data on the database. Anyway I can fix this?
This is my php code.
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
$searchKeyword = $_POST['find']; // Sanitize this value first !!
$sql=mysqli_query($link, "Select * FROM Locations WHERE `Animal_Type` LIKE '%$searchKeyword%' ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal_Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
//}
?>
Just make sure $searchKeyword has a (valid) value
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
// checks to see if $_POST['find'] is actually set.
if ( array_key_exists('find',$_POST) )
{
$searchKeyword = $_POST['find']; // Sanitize this value first !!
// sanitize $searchKeyword here
}
// checks to see if $searchKeyword has no value, or just contains empty space
if ( empty(trim($searchKeyword)) )
{
echo "You must enter a search term";
}
else
{
$sql=mysqli_query($link, "Select * FROM Locations WHERE `Animal_Type` LIKE '%$searchKeyword%' ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal_Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
}
?>
Try removing the "%" from either the back or the front of the $searchKeyword in the query and I guess it should do the work.
"%" is used when match all or none. So if you send an empty string it will return the whole database.

PHP-mysql_fetch_array return nothing

I've trying to display values from mysql but it return any empty page. The connection is fine but it does not fetch the data from mysql. I tried all the answers from the similar questions asked. But nothing helped. Can somebody please help me? This is the code
$con= mysql_connect($host, $username, $pwd);
if(!$con)
die("not connected". mysql_errno());
echo(Connected);
mysql_select_db("info",$con);
$query="select * from people";
$result= mysql_query($query,$con) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['id']. " - ". $row['people_name'];
echo "<br />";
}
Try to check if your db user,password are correct! I test the code above :
<?php $con=mysqli_connect("localhost","root","","test"); // Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM people");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " -- " . $row['people_name']; echo "<br>";
}
?>
and give me the result without error: 10 -- JOHN 11 -- PRADEEP
I just change mysql_connect to mysqli_connect add in $con= mysql_connect($host, $username, $pwd); a dbname. and $con become $con= mysqli_connect($host, $username, $pwd,$dbname); I use mysqli_query instead of mysql_query. Here is a stackQuestion for the mysql vs mysqli in php which can explain you the difference.
Try this
<?php
$con= mysql_connect('hostname', 'username', 'password');
if(!$con)
die("not connected". mysql_errno());
echo("Connected");
mysql_select_db("test",$con);
$query="select * from tabale_name";
$result= mysql_query($query,$con) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
?>
check this
<?php
$con=mysqli_connect("hostname","username","password","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM people");
while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['people_name'];
echo "<br>";
}
?>
OR
<?php
$con=mysqli_connect("hostname","username","password");
// Check connection
if ($con)
{
echo "connected to db";
}
else
{
echo "not connected to db";
}
$db_selected = mysql_select_db("info", $con);
if (!$db_selected)
{
die ("Can\'t use info: " . mysql_error());
}
$result = mysqli_query("SELECT * FROM people");
while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['people_name'];
echo "<br>";
}
?>

How to Post data from a php database populated Drop Down to another script?

I created a PHP Drop Down which is populated from a MySql Database and works just fine, the problem occurs when I want to post the selected in another script. The question is how to post the data to the other script?
This is the source code of the script that implements the drop downs. Please Help!!!!
<?php
$conn = mysql_connect("localhost", "admin", "admin");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekupuvac")) {
echo "Unable to select EKupuvac: " . mysql_error();
exit;
}
$query = "SELECT ImeK, KupuvacID FROM kupuvac ORDER BY Saldo DESC";
$result = mysql_query($query) or die(mysql_error());
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so I am exiting";
exit;
}
$dropdown = "<select name='ImeK'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown.= "\r\n<option value='{$row['KupuvacID']}'>{$row['ImeK']}</option>";
}
$dropdown .= "\r\n</select>";
echo"Izberi Kupuvac:";
echo $dropdown;
// Second Combo
$conn = mysql_connect("localhost", "admin", "admin");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekupuvac")) {
echo "Unable to select EKupuvac: " . mysql_error();
exit;
}
$query2 = "SELECT ImeP, ProzivodID FROM proizvod ORDER BY ImeP";
$result2 = mysql_query($query2) or die(mysql_error());
if (!$result2) {
echo "Could not successfully run query ($query2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so I am exiting";
exit;
}
$dropdown2 = "<select name='ImeP'>";
while($row = mysql_fetch_assoc($result2)) {
$dropdown2.= "\r\n<option value='{$row['ProzivodID']}'>{$row['ImeP']}</option>";
}
$dropdown2.= "\r\n</select>";
echo"<br> Izberi Proizvod:";
echo $dropdown2;
echo"<br>";
mysql_free_result($result);
?>
A <select> box is not enough, you need to enclose it in a form
?>
<form method="post" action="somescript.php">
<?
//your controls go here
?>
</form>
then create somescript.php and access your form variables using $_POST
Also use PDO not mysql_ functions as these arent safe

Categories