I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name" >
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";
Related
I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer
i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.
The structure is as follows:
HTML
<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
<?php
$ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
$result = mysqli_query($con, $ogrodysql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
}
}
else {
echo "0 results";
}
?>
<br><br>
<input type="submit" value="Usuń zaznaczony ogród."/>
</form>
PHP for processing form in usunogrod.php
<?php
$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);
$database = 'xxxxx';
if (!mysqli_connect($db_host, $db_user, $db_pwd))
die("Brak połączenia z bazą danych.");
if (!mysqli_select_db($con, $database))
die("Nie można wybrać bazy danych.");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ogrod_id = trim(sql_safe($_POST['removegarden[]']));
if (isset($_POST['removegarden[]'])) {
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");
$msg = 'Ogród został usunięty.';
}
elseif (isset($_GET['removegarden[]']))
$msg = 'Nie udało się usunąć ogrodu.';
};
?>
MySQL table
ogrody
# id_ogrodu nazwa
1 garden1
How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?
EDIT:
I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.
I think this should help you:
Change this line:
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
For this one:
echo '• ' . $row["id_ogrodu"]. ' ' . $row["nazwa"]. '<input type="checkbox" name="removegarden['.$row["id_ogrodu"].']" value="'.$row["id_ogrodu"].'" /> <br/><br/>';
Then this one:
if (isset($_POST['removegarden[]'])) {
To
if (isset($_POST['removegarden'])) {
And finally your query:
$gardens = implode(',',$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN($gardens)");
You can get your data in $_POST['removegarden']. no need [] at last.
Then convert this array to ',' seperated string which can be then used in query
if (isset($_POST['removegarden'])) {
$ids_to_delete = implode(",",$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN ($ids_to_delete)");
$msg = 'Ogród został usunięty.';
}
I have a dropdown called product1 and a textbox called price1. The dropdown is filled with products from the database. I want to show the price of te selected product in the textbox called 'price1'.
I am using the following table structure:
forms (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sort` int(1) NOT NULL,
`name` varchar(100) NOT NULL,
`prices` decimal(7,2) NOT NULL,
`tax` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
With the following code I am trying to fill the textbox with the selected value.
//filename: test.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms WHERE id='". $product1 ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div id='price-list'>";
echo "<input type='text' class='form-control' name='price1' id='price1' value='" . $row["price"]. "'>";
echo "</div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<script>
function getprice(val) {
$.ajax({
type: "POST",
url: "test.php",
data:'id='+val,
success: function(data){
$("#price-list").html(data);
}
});
}
</script>
<?php
$product1=$_POST['price1'];
?>
When I select a product in dropdown, nothing is happening.
Can anyone help me to fix this code?
Thanks!
Update 1: Still not working
//filename: index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<!-- Your text input -->
<input id="product_name" type="text">
</html>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.select2 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
And
//filename: get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$productId = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
$query = 'SELECT price FROM forms WHERE id=' . $productId;
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$result = mysql_fecth_assoc($res);
print($result['price']);
die();
}
?>
Try this:
On your select you are putting the callback for onchange, use it to call a javascript function and in this funcion get the value and populate your text field.
...
<select class='form-control select2' id='product1' name='product1'
onchange='changeValue();' style='width: 100%;'>
<!-- Your text input -->
<input id="product_name" type="text">
...
function changeValue() {
// getting the selected text in combo
var selectedItem = jQuery('.select2 option:selected').text;
// and putting in text field
jQuery('#product_name').val(selectedItem);
}
While you have all in the same script test.php you probably introduced the basic problem that you do not distinguish between…
the case when you are setting up the page (first call) with the product list and
the case when you are posting the product id to get the price (AJAX call, whenever the user chooses a different product).
The two cases can be distinguished by the presence of the variable $_POST['id'] (isset($_POST['id']). The variable $_POST['price1'] however is never transmitted and used.
I've puzzled it together (without having it tested). Try it out:
<?php
//filename: test.php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!isset($_POST['id'])) { // First call: setup the page -----------------------------
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
echo '<html>
<head>
<script>
function getprice(val) {
$.ajax({
type: "POST",
url: "test.php",
data:\'id=\'+val,
success: function(data){
$("#price-list").html(data);
}
});
}
</script>
</head>
<body>
';
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
echo "<select class='form-control select2' id='product1' name='product1' onChange='getprice(this.value);' style='width: 100%;'>";
if ( ($result!==false) && ($result->num_rows > 0) ) {
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
}
if ($result) mysqli_free_result($result);
echo '</select>';
echo '<div id="price-list">';
echo '</div>';
echo '</body>
</html>
';
} else { // Ajax call, $_POST['id'] is set -------------------------
$product1 = $_POST['id'];
$sql = "SELECT * FROM forms WHERE id='". $product1 ."'";
$result = $conn->query($sql);
if ( ($result!==false) && ($result->num_rows > 0) ) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<input type='text' class='form-control' name='price1' id='price1' value='" . $row["price"]. "'>";
break;
}
} else {
echo "0 results";
}
if ($result) mysqli_free_result($result);
}
$conn->close(); // Drop connection
?>
After read your comments I understand that what you need is to get the product price when the combo is changed, but you still don't have these prices. So you can to do an Ajax request to get the price.
...
<select class='form-control select2' id='product1' name='product1'
onchange='getPrice();' style='width: 100%;'>
<!-- Your text input -->
<input id="product_name" type="text">
...
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.select2 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'your-php-file-to-do-query-in-database.php',
method: 'POST',
data: 'product_id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
In you PHP file you must to make a query in database to get product price.
$productId = filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT);
$query = 'SELECT price FROM products WHERE id=' . $productId;
//execute the query in database and return the result
// In this example I will suppose you used the mysql_* functions
// to get the price
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$result = mysql_fecth_assoc($res);
print($result['price']);
// and finally ends the script
die();
}
I hope this help you.
I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
i have two tables
students table
csci01members table
I will put the student record in the csci01members, my code doesn't have a syntax error.
But it always get's stuck in "The user is already a member". EVEN if he's not ,I already got the code of adding the record.
but i need an error trapping so that if the user is
already in the csci01members table. it can't add the record or
he cannot view the members of csci01 so that the member already will not be seen
in the list of adding into table.
<?php
$errors="";
if(isset($_GET['add']))
{
$con = mysql_connect("localhost","root","");
if(!$con)
{ die("could not connect to server".mysql_error()); }
mysql_select_db("login", $con);
if (empty($errors)){
$check = mysql_query("SELECT * from csci01members");
$check_count = mysql_num_rows($check);
if ($check_count == 1) {
die (" The user is already a member.");
}
}
$result = mysql_query("SELECT * from students where username='$_GET[add]'");
$result_count = mysql_num_rows($result);
if ($result_count == 0) {
echo "<font color=red><br /> The user doesn't exists.</font>";
}
else
{
while($row = mysql_fetch_array($result))
{
echo "Student Number: $row[username]<br>Name: $row[namelast]
, $row[namefirst]<br><br> was added to the group<br><br>";
$sn = $row['username'];
$nl = $row['namelast'];
$nf = $row['namefirst'];
$nm = $row['namemi'];
mysql_query("INSERT INTO csci01members (username, namelast, namefirst, namemi)
VALUES ('$sn', '$nl', '$nf', '$nm')");
mysql_close($con);
}
}
}
$con = mysql_connect("localhost","root","");
if(!$con)
{ die("could not connect to server".mysql_error());}
mysql_select_db("login", $con);
$sql="Select * from students";
$sql_result=mysql_query($sql)
or exit("Sql Error".mysql_error());
$sql_num=mysql_num_rows($sql_result);
if($row = mysql_num_rows($sql_result) == 0)
{
echo "There are no registered student yet<br><br>";
$name=$row["username"];
$class=$row["namelast"] .$row["namefirst"];
$accept = "<a href='?add=$row[username]'> </a>";
}
else
{
echo "<table border = 0 width=\"200%\">";
echo "<tr>";
echo "<td width = '20%' > <b><center>USN</center></b></td>
<td width = '60%'><b><center>Name</center></b></td>
<td width = '10%'><b><center>Action</center></b></td>";
echo "</tr>";
while($sql_row=mysql_fetch_array($sql_result))
{
$name=$sql_row["username"];
$class=$sql_row["namelast"] . ', '.$sql_row["namefirst"];
$accept = "<a href='?add=$sql_row[username]'>[Add]</a>";
echo "<td >".$name."</td>";
echo "<td>".$class."</td>";
echo "<td>".$accept."</td></tr>";
}
}
echo "</table>";
mysql_close();
?>
Your "count_check" count all rows in table, you needs count rows with added username
if (empty($errors)){
$check = mysql_query("SELECT * from csci01members WHERE username = '".mysql_real_escape_string($_GET['add'])."'");
$check_count = mysql_num_rows($check);
if ($check_count == 1) {
die (" The user is already a member.");
}
}
And for add identificator better use numeric id. Username may contain special symbols like space or something else, and when you will pass them by url, them being encoded