I am stuck with how to insert multiple array data of checkbox. I came across some code but I don't know how to implement them in my php code. How can I insert multiple data from checkbox in my database? Can someone help me? I really appreciate it. Thank you in advance.
html code:
<?php
include ('connect.php');
$sql2 = "SELECT * FROM owner WHERE owner_username ='".$_SESSION['username']."'";
$result2 = mysqli_query($conn,$sql2);
$row = mysqli_fetch_array($result2);
$id = $row['owner_id'];
$sql = "SELECT cat_id,name,gender,health_status,neutered,breed,color,age
FROM cat WHERE owner_fk = '$id'";
$result = $conn-> query($sql);
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
echo "<tr>";
echo "<td>" .$row ['name']. "</td>";
echo "<td>" .$row ['gender']. "</td>";
echo "<td>" .$row ['health_status']. "</td>";
echo "<td>" .$row ['neutered']. "</td>";
echo "<td>" .$row ['breed']. "</td>";
echo "<td>" .$row ['color']. "</td>";
echo "<td>" .$row ['age']. "</td>";
echo "<td>" ."<input type='checkbox' name= 'check[]' value=''". "
</td>";
echo "</tr>";
}
echo "</table>";
}
else{
echo "0 result";
}
$conn-> close();
?>
this is my php code:
<?php
include ('connect.php');
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST["check"]);$i++)
}
$p_id =$_GET ['sitter'];
$price = $_POST ['price'];
$pickup_date =$_POST ['pickup_date'];
$dropoff_date =$_POST ['dropoff_date'];
$numdays = $_POST ['numdays'];
$total =$_POST ['test'];
$sql2 = "INSERT INTO cat_sitter(sitter_fk,cat_fk, price, date_in,
date_out,total_day, total)VALUES ('$p_id','".$_POST["check"]
[$i]."','$cat_id','$price','$pickup_date','$dropoff_date','$numdays',
'$total')" or die ("Error inserting data into table");
if ($conn->query($sql2) === TRUE) {
echo "<script language='javascript'>alert('Succesfully Book.')
window.location.replace(\"book_page.php\");
</script>";
}else{
echo "error: " . $sql2 . "<br>" . $conn->error;
}
?>
Use implode function
In your case replace $_POST["check"] with implode(',',$_POST["check"]) then it will work fine fine hope so
Instead of implode and explode. You can use convert checkbox array into JSON and store in single field.
// Convert Array to JSON String
$checkArray = $_POST["check"];
$checkJSON = json_encode($checkArray);
After you fetch its value from database convert JSON into array.
// Convert JSON string to Array
//$checkJSON is variable fetched from database
$checkArray = json_decode($checkJSON, true);
print_r($checkArray); // Dump all data of the Array
Related
<?php
$con = new mysqli('localhost', 'root' ,'', 'world');
$query = 'SELECT * FROM city ORDER BY Name';
if ($result = mysqli_query($con, $query)) {
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>"
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
mysqli_close($con);
?>
This simple code will display every entries in this database. Now I would like to add a selective display option by choosing the CountryCode.
$query2 = 'SELECT DISTINCT CountryCode FROM city ORDER BY CountryCode';
How do I use the result I got from the query above and make it become radio buttons to choose what to display?
Similar to what you are doing already: Something like
while ($row = mysqli_fetch_assoc($result)) {
echo "<input type='radio' name='whatever' value='".$row['Name']."'>". $row['Name'];
}
Ofcourse the field names can be whatever you like them to be, as long as you select them in the query
I have created an sql database(with phpmyadmin) filled with measurements from which I want to call data between two dates( the user selects the DATE by entering in the HTML forms the "FROM" and "TO" date) and display them in a table.
Additionally I have put, under my html forms, some checkboxes and by checking them you can restrict the amount of data displayed.
Each checkbox represent a column of my database; so along with the date and hour column, anything that is checked is displayed(if none is checked then everything is displayed).
So far I managed to write a php script that connects to the database, display everything when none of my checkboxes is checked and also managed to put in order one of my checkboxes.
Problem: The data that I call for are been displayed twice.
Question: I want to have four checkboxes.
Do I need to write an sql query for every possible combination or there is an easier way?
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_Database_Test = "localhost";
$database_Database_Test = "database_test";
$table_name = "solar_irradiance";
$username_Database_Test = "root";
$password_Database_Test = "";
$Database_Test = mysql_pconnect($hostname_Database_Test, $username_Database_Test, $password_Database_Test) or trigger_error(mysql_error(),E_USER_ERROR);
//HTML forms -> variables
$fromdate = $_POST['fyear'];
$todate = $_POST['toyear'];
//DNI CHECKBOX + ALL
$dna="SELECT DATE, Local_Time_Decimal, DNI FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$tmp ="SELECT * FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$entry=$_POST['dni'];
if (empty($entry))
{
$result = mysql_query($tmp);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>Solar_time_decimal</th>
<th>GHI</th>
<th>DiffuseHI</th>
<th>zenith_angle</th>
<th>DNI</th>
";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
echo "<td>" . $row['Solar_Time_Decimal'] . "</td>";
echo "<td>" . $row['GHI'] . "</td>";
echo "<td>" . $row['DiffuseHI'] . "</td>";
echo "<td>" . $row['Zenith_Angle'] . "</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';}
else
{
$result= mysql_query($dna);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>DNI</th>
";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal']."</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';
}
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();
?>
Try to create your checkbox like below:
Solar_Time_Decimal<checkbox name='columns[]' value='1'>
GHI<checkbox name='columns[]' value='2'>
DiffuseHI<checkbox name='columns[]' value='3'>
Zenith_Angle<checkbox name='columns[]' value='4'>
DNI<checkbox name='columns[]' value='5'>
And try to hange your PHP code to this:
<?php
//HTML forms -> variables
$fromdate = isset($_POST['fyear']) ? $_POST['fyear'] : data("d/m/Y");
$todate = isset($_POST['toyear']) ? $_POST['toyear'] : data("d/m/Y");
$all = false;
$column_names = array('1' => 'Solar_Time_Decimal', '2'=>'GHI', '3'=>'DiffuseHI', '4'=>'Zenith_Angle','5'=>'DNI');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "DATE,Local_Time_Decimal";
}
//DNI CHECKBOX + ALL
$tmp ="SELECT ".implode(",", $sql_columns)." FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$result = mysql_query($tmp);
echo "<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();?>
This solution consider your particular table columns but if your wish a generic solution you can try to use this SQL too:
$sql_names = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database_Database_Test' AND TABLE_NAME = '$table_name'";
and use the result to construct the $column_names array.
Solution for your problem : Change the mysql_fetch_assoc with mysql_fetch_array
If you have the same problem try to print your result with print_r
Answer : Use the bit datatype in mysql for store and read your checkboxes.
When you're receiving thr value from the database then you can use
in the parameter checked you can use the php code as exist :
$value = ...get the value from db ( 1 or 0 )
echo '<input type="checkbox" name="thename" value="thevalue" '.($value==1?'checked=checked'.'').'/>';
I have a simple php script which performs a simple SQL query twice. Query works perfectly for the first but for the second time error appears;
Notice: Trying to get property of non-object in C:\apache\localhost\www\study.kg\webstore\web_store.php on line 48
Fatal error: Call to a member function free() on a non-object in C:\apache\localhost\www\study.kg\webstore\web_store.php on line 80
First, we make a query to 'categories' table. Everything is good.
Second, we make the same query to 'shoes' table. Everything is bad, because
$query = "SELECT * FROM shoes";
$result = $db->query($query);
returns FALSE value.
But why? The first it worked perfectly. The tables are the same, if you mean encoding and etc. So, as you can guess, my first table displays itself perfectly, second table doesn't show any data at all.
Here is a full snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Лабораторная: интернет-магазин обуви</title>
</head>
<body>
<?php
#$db = new mysqli('localhost', 'dzhakipov', 'asd12345', 'webshop');
if (mysqli_connect_errno()) {
echo 'Error: could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM categories";
$result = $db->query($query);
$num_results = $result->num_rows;
?>
<table>
<tr>
<td>id</td>
<td>Название</td>
<td>Описание</td>
<td>Поставщик</td>
<td>Продавец</td>
<td>Адрес склада</td>
</tr>
<?php
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<tr>";
echo "<td>" .stripslashes($row['id']). "</td>";
echo "<td>" .htmlspecialchars(stripslashes($row['name'])). "</td>";
echo "<td>" .stripslashes($row['description']). "</td>";
echo "<td>" .stripslashes($row['supplier']). "</td>";
echo "<td>" .stripslashes($row['salesman']). "</td>";
echo "<td>" .stripslashes($row['storage_address']). "</td>";
echo "</tr>";
}
echo "</table>";
$query = "SELECT * FROM shoes";
$result = $db->query($query);
$num_results = $result->num_rows; // LINE 48 #############################
?>
<table>
<tr>
<td>id</td>
<td>categoryid</td>
<td>Название</td>
<td>Пол</td>
<td>Размер</td>
<td>Сезон</td>
<td>Внешний материал</td>
<td>Внутренний материал</td>
<td>Цвет</td>
<td>Описание</td>
</tr>
<?php
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<tr>";
echo "<td>" .stripslashes($row['id']). "</td>";
echo "<td>" .stripslashes($row['categoryid']). "</td>";
echo "<td>" .htmlspecialchars(stripslashes($row['name'])). "</td>";
echo "<td>" .stripslashes($row['sex']). "</td>";
echo "<td>" .stripslashes($row['size']). "</td>";
echo "<td>" .stripslashes($row['season']). "</td>";
echo "<td>" .stripslashes($row['inner_material']). "</td>";
echo "<td>" .stripslashes($row['outer_material']). "</td>";
echo "<td>" .stripslashes($row['colour']). "</td>";
echo "<td>" .stripslashes($row['price']). "</td>";
echo "</tr>";
}
echo "</table>";
$result->free(); // LINE 80 #############################
$db->close();
?>
</body>
</html>
Thanks for attention.
See this http://php.net/manual/en/function.mysql-free-result.php before using result for the second time.
You also can change the second $result into $result2 to let It work.
I'd try freeing the first result before querying for the second
$result->free();
$query = "SELECT * FROM shoes";
$result = $db->query($query);
Second, though I'm not familiar with mysqli (big PDO fan here), I believe false might be a possible result of a query, so you should wrap the result traversing in an if block.
if($result) {
$num_results = $result->num_rows;
...
$result->free();
}
As you store your MySQL query as a String in $Query variable now for the php to execute this query you need to use mysqli_query() that will retrieve data from DB
I have selected a random table from a list/array and I want to be able to call this random table with the mysqli_query function i.e. select a table dynamically
Here is my code:
<?php
$mysqli=mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Looks at all prodcuts and selects those that have special offers enabled
// Selects a random table from the array
$tables_special = ["ajbs_products_console" ,"ajbs_products_console_games", "ajbs_products_pc", "ajbs_products_pc_games", "ajbs_products_pc_parts"];
$rtable = $tables_special[floor (rand(0,count($tables_special)-1))];
echo "<p>".$rtable." was selected</p>";
$products = mysqli_query("SELECT * FROM '".$rtable."'");
echo "<p>".$products."</p>";
while($productRow = mysqli_fetch_array($products))
{
if ($productRow['product_specials'] == 1)
{
echo "<table>";
echo "<tr>";
echo "<td rowspan='2'><img src=" . $productRow['product_image'] . "/></td>";
echo "</tr>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>" . $productRow['product_name'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>" . $productRow['product_description'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($mysqli);
?>
Im at a loss of why this is not working
Thanks,
Bull
You should not quote table names with single quotes but with backticks, single quotes makes it a string instead of a table name;
Also, the function mysqli_query takes an extra parameter, the connection.
$products = mysqli_query("SELECT * FROM '".$rtable."'");
should be;
$products = mysqli_query($mysqli, "SELECT * FROM `".$rtable."`");
Try
$products = mysqli_query($mysqli, "SELECT * FROM ".$rtable);
Can someone please help me on the following code? Simply put, I'm trying to get two separate SQL tables' data, one on the horizontal side (brands) and the other (distributors) on the vertical side of a dynamically populated table.
my issue is, if you go through the code I cant get the text boxes populated under each respective brand name I get to display from the database. The text boxes are appearing only for the first brand name column.
My second issue if how do I assign a unique ID or a name to a dynamically populated text box here?
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
{
echo "<td>" . $rowq['bname'] . "</td>";
}
"</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='txt1'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
You're creating loop without relating to eachother, and the same goes for the execution of the querys...
If you want to solve it you will have to nestle the loops together, something like:
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
echo "<td>" . $rowq['bname'] . "</td>";
//Show all brands for current distributor
$sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
$resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");
while($row = mysqli_fetch_array($resultBrands))
{
$id = $row['rsm'];
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
//End show all brands for current distributor
}
//End Go through all distributors
A better solution though, would be something like (of course $q has to validated before input inside of query and also binded with bind_param()).
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");
echo "<table border='1'>";
while($rowq = mysqli_fetch_array($result))
{
$id = rowq['rsm'];
echo "<tr>";
echo "<td>" . $rowq['dname'] . "</td>";
echo "<td>" . $rowq['bname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
Take notice of the name='textBox[]'. From PHP you can access the variable with $_POST['textBox'] (or $_GET['textBox'] and PHP will return an array).