How to build a dynamic MySQL INSERT statement with PHP - php

Hello
This part of a form is showing columns names from mysql table (names of applications installed on a computer) and creating a form with YES/NO option or input type="text" box for additional privileges to a application..
How can I insert it back to a mysql table using POST and mysql_query INSERT INTO?????
Quantity of columns is changing because there is another form for adding applications with/without privileges..
<tr bgcolor=#ddddff>';
//mysql_query for getting columns names
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
//exclude these columns bcs these are in other part of form
if($row[0] == 'id' || $row[0] == 'nameandsurname' || $row[0] == 'department'
|| $row[0] == 'phone' || $row[0] == 'computer' || $row[0] == 'data')
continue;
echo '<td bgcolor=#ddddff>'.$row[0].'<br />';
if (stripos($row[0], "privileges") !== false) {
echo '<td bgcolor=#ddddff><p><a class=hint href=#>
<input type="text" name="'.$row[0].'">
<span>Privileges like "occupation" or "like someone"</span></a></p></td></tr>';
}
else
{
echo '<td bgcolor=#ddddff align=center><select name="'.$row[0].'">
<option value = "No">No
<option value = "Yes">Yes
</td>
</tr>';
}
}
trim($_POST); // ????
$query = "INSERT INTO 'employees' VALUES (??)"; // ????

Because you're not inserting ALL columns, you need to dynamically build an insert statement that will specify the columns you're inserting into.
First, create an array of the columns you want to use. Use this both to generate your form and to retrieve the values
$exclude = array("id", "nameandsurname", "departument", "phone", "computer", "date");
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
$columns = array();
while ($row = mysql_fetch_array($result)) {
if (!in_array($row[0], $exclude) {
$columns[] = $row[0];
}
}
Render your form from the $columns array:
foreach ($columns as $column) {
echo '<tr><td bgcolor="#ddddff">'.$column.'<br />';
if (stripos($column, "privileges") !== false) {
echo '<p><a class="hint" href="#">
<input type="text" name="'.$column.'">
<span>Privileges like "occupation" or "like someone"</span></a>';
} else {
echo '<select name="'.$column.'">
<option value = "No">No
<option value = "Yes">Yes
</select>';
}
echo '</td></tr>';
}
Then, dynamically build your INSERT string from the posted values for those columns. Be sure to protect against SQL injection:
$keys = array();
$values = array();
foreach ($columns as $column) {
$value = trim($_POST[$column]);
$value = mysql_real_escape_string($value);
$keys[] = "`{$column}`";
$values[] = "'{$value}'";
}
$query = "INSERT INTO 'employees' (" . implode(",", $keys) . ")
VALUES (" . implode(",", $values) . ");";
Note: this will work better if you select from INFORMATION_SCHEMA.COLUMNS so that you can know the type of column you're inserting into. That way, you won't have to quote everything.

<html>
<body>
<form action="dynamicinsert.php" method="POST" >
user name:<br>
<input type="text" id="username" name="username">
<br><br>
first name:<br>
<input type="text" id="firstname" name="firstname">
<br><br>
password:<br>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" name="submit" value="add" />
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "you_DB_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function insertqueryfunction($dbfield,$table) {
$count = 0;
$fields = '';
foreach($dbfield as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$col = addslashes($col);
$val = addslashes($val);
$fields .= "`$col` = '$val'";
}
$query = "INSERT INTO $table SET $fields;";
return $query;
}
if(isset($_POST['submit']))
{
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
$username_form = $_POST['username'];
$firstname_form = $_POST['firstname'];
$password_form = $_POST['password'];
$you_table_name = 'you_table_name';
$dbfield = array("username"=>$username_form, "firstname"=>$firstname_form,"password"=>$password_form);
$querytest = insertqueryfunction($dbfield,'you_table_name');
if ($conn->query($querytest) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>

Related

How to create dynamic insert query using php and mysql? [duplicate]

hi friends i'm creating a php page to import the data from a csv file into sql database..
here database table and number of fields are specified by user itself..
if user specifies 4 fields, then it is created using a for loop as follows..
<?php
include('connect.php');
$name = $_POST['table_name'];
//echo $name;
$create_tab = "CREATE TABLE $name(id varchar(15) PRIMARY KEY)";
if(mysql_query($create_tab,$con))
{
echo "Table <b><i>$name</i></b> created successfully... <br/> <br/>Add columns...";
}
else {
die('Error1'.mysql_error());
}
$field = $_POST['number_of_fields'];
//echo $name.$field;
echo '<form id="form1" name="form1" method="post" action="update-table.php">';
echo "<p>
<label for='tablename'></label>
<input type='hidden' name='tablename' id='tablename' value='$name' size='5'/>
</p>";
echo "<p>
<label for='fields'></label>
<input type='hidden' name='fields' id='fields' value='$field' size='5'/>
</p>";
echo '<table border="1" cellpadding="5" cellspacing="5">';
for ( $i = 1; $i <= $field; $i ++) {
echo '<tr>';
echo '<td>';
echo "<p>
$i
</p>";
echo'</td>';
echo '<td>';
echo "<p>
<label for='textfield$i'></label>
<input type='text' name='field$i' id='textfield$i' />
</p>";
echo'</td>';
echo '<td>';
echo "
<select name='select$i' id='select$i'>
<option value='varchar(200)'>varchar</option>
<option value='int'>int</option>
<option value='float'>float</option>
<option value='date'>date</option>
</select>";
echo '</td>';
echo '</tr>';
}
echo '</table>';
?>
<p>File Location :
<input type="text" name="fileField" id="fileField" />
</p>
<br/>
<INPUT type="image" name="search" src="images/alter.gif" border="0" height="75" width=120">
</form>
then table create and alter as follows..
<?php
include('connect.php');
$field = $_POST[fields];
$name = $_POST[tablename];
for ( $i = 1; $i <= $field; $i++) {
//getting field names
$varname = ($txtfield . $i);
$$varname = $_POST[field.$i];
// echo $$varname;
$fi = $$varname;
//getting field types
$selname = ($selfield . $i);
$$selname = $_POST[select.$i];
$dt = $$varname;
$sql = "ALTER TABLE $name ADD $fi $dt";
if(mysql_query($sql,$con))
{
echo "Field <b><i>$fi</i></b> added successfully...<br/>";
}
else {
die('Error1'.mysql_error());
}
}
?>
as above database table and fields are crated...
i got the concept of inserting data using static variables as follows..
<?php
// data import
include('connect.php');
$field = $_POST['fileField']; //file directory
echo "<br/><br/>Import file path: ";
echo $field;
$file = $field;
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
// ' escape character
if (strpos($column2, "'") == FALSE)
{
$column21 = $column2;
}
else{
$column21 = str_replace ("'", "\'", $column2);
}
$column3= $arr[2];
$column4= $arr[3];
//print data from csv
echo "<table border='1' width='800' cellpadding='5' cellspacing='2'>";
echo "<tr>";
echo "<td width='8'>";
echo $column1;
echo "</td>";
echo "<td width='100'>";
echo $column21;
echo "</td>";
echo "<td width='5'>";
echo $column3;
echo "</td>";
echo "<td width='5'>";
echo $column4;
echo "</td>";
echo "</tr>";
echo "</table>";
$import="INSERT into $name (id,name,year1,year2) values(
'$column1','$column21','$column3','$column4')";
mysql_query($import) or die(mysql_error());
}
?>
now, my question is how can i make this insert statement dynamic as such it creates field names and values dynamically inside insert query from the data obtained from for loop in table create and alter query???
If I understand your question correctly, it sounds like you want to combine your inserts into one query (which is very smart performance wise). SQL allows you to insert multiple rows at once like so:
INSERT INTO table (id, first, last) VALUES(NULL, 'Ryan', 'Silvers'),(NULL, 'Oscar', 'Smith'),(NULL, 'Jessica', 'Owens')
So by using creating an array of VALUES and using implode to join them you can make one query:
//Create rows
foreach($rows as $row) {
$queryRows[] = "(NULL, '".$row['first']."', '".$row['last']."')";
}
//Create query
$query = 'INSERT INTO table (id, first, last) VALUES'.implode(',', $queryRows);
Now that I understand your real question, I can give you a basic overview of what you need to do to achieve this. You need to create a form that allows a user to enter data that will be inserted into the table.
<form method="post" action="process.php">
<input name="field1" />
<!-- and more -->
</form>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
<?php
//Check form submission and validate entries, then...
$stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
$stmt->execute(array(':field1', $_POST['field1']));
?>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
function insert($tablet,$datad)
{
if(empty($tablet)) { return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$query1 = "select * from user";
$result1 = mysql_query($query1);
$numcolumn = mysql_num_fields($result1);
$addd = "";
$count = 0;
for ( $i = 1; $i < $numcolumn; $i++ )
{
$columnnames = mysql_field_name($result1, $i);
if(($numcolumn-1) == $i)
{
$addd .= $columnnames;
$data .= "'".$datad[$count]."'";
}
else
{
$addd .= $columnnames.",";
$data .= "'".$datad[$count]."',";
}
$count++;
}
$ins = "INSERT INTO ".$tablet."(".$addd.")"."VALUES(".$data.")";
mysql_query($ins);
header('Location: index.php');
exit;
}

PHP Multiple input search

I'm currently working on a bit of PHP and I've 3 text inputs. The values are searched in the MySQL database and should return whatever amount of results correspond with the entered criteria.
here is the search form:
<form id='SearchPersonal' method='post' action='businessUsersSearch.php' accept-charset='UTF-8'>
<fieldset >
<legend>Search</legend>
<div class='container'>
<label for='C_Name' >Business Name: </label><br/>
<input type='text' name='C_Name' id='C_Name' maxlength="50" /><br/>
<label for='C_County' >City: </label><br/>
<input type='text' name='C_County' id='C_County' maxlength="50" /><br/>
<label for='Job_Type' >Job Type: </label><br/>
<input type='text' name='Job_Type' id='Job_Type' maxlength="50" /><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Search' />
</div>
</fieldset>
</form>
Here is the PHP script it links too in the action:
<?php
$mysqli_link = mysqli_connect("server", "database", "pass", "user");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_County', 'Job_Type');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// builds the query
$query = "SELECT C_Name, C_StreetNumber, C_StreetName, C_Postcode, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Jobs.Job_Type, Jobs.Job_Price FROM Company INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysqli_query($mysqli_link, $query) or die(mysql_error());
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_assoc($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<hr><br>";
}
}
}
?>
For some reason it is returning that there is "
unexpected end of file
" however I've checked the code and all the codes is closed off correctly (from what I can see) when I add another '}' in at the end the script doesn't return anything at all. Anyone know why this would be happening?
Source:
Search MySQL Database with Multiple Fields in a Form
Because you forget to close
if(isset($_POST['submit'])) {// you not close the condition
At the end of your file
Just add } at end of your file
Fixed:
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_City', 'Job_Type', 'Review_Rate');
$conditions = array();
}
// builds the query
$query = "SELECT Company.C_Name, Company.C_StreetNumber, C_StreetName, C_Postcode, C_City, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Job_Type, Job_Price, Review_Rate, Review_Comment
FROM Company
INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID
INNER JOIN Review ON Jobs.Job_ID = Review.Job_ID";
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "$query";
$result = mysqli_query($mysqli_link, $query);
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_array($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_City = $row['C_City'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
$Rating = $row['Review_Rate'];
$Comment = $row['Review_Comment'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>City: $C_City<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<br>Rating: $Rating<br>Comment: $Comment<hr><br>";
}
}
?>

How to display certain rows from mysql with variable sent via HTML form

I'm trying to get certain data which meets the criteria from the database using AND condition with user searchable HTML form which sends the data to the search.
Code:
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
if (isset($_POST['Kohderyhmä']) &&
isset($_POST['Näytön aste']) &&
isset($_POST['Vaikutusten vahvuus']) &&
isset($_POST['Käyttökelpoisuus']) &&
isset($_POST['text']))
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
$Näytön_aste = get_post($conn, 'Näytön aste');
$Vaikutusten_vahvuus = get_post($conn, 'Vaikutusten vahvuus');
$Käyttökelpoisuus = get_post($conn, 'Käyttökelpoisuus');
$text = get_post($conn, 'text');
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='$Kohderyhmä' AND `Näytön aste`='$Näytön_aste' AND `Vaikutusten vahvuus`='$Vaikutusten_vahvuus' AND `Käyttökelpoisuus: luokka`='$Käyttökelpoisuus'";
}
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
echo '<h3>' . $row['Nimi'] . '</h3><br />';
echo '' . $row['Kokonaisarvio'] . '<br />';
echo '' . $row['Kuvaus'] . '<br /><br />';
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<b>Kohderyhmä</b><br />
<select name="Kohderyhmä" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Pikkulapset">Pikkulapset</option>
<option value="Alle kouluikäiset">Alle kouluikäiset</option>
<option value="Alakouluikäiset">Alakouluikäiset</option>
<option value="Nuoret">Nuoret</option>
<option value="Perheet">Perheet</option>
<option value="Vanhemmat">Vanhemmat</option>
<option value="Työntekijät">Työntekijät</option>
</select>
<br />
<b>Näytön aste</b>
<select name="Näytön aste" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei riittävää näyttöä">Ei riittävää näyttöä</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Vaikutusten vahvuus</b>
<select name="Vaikutusten vahvuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei vaikutusta">Ei vaikutusta</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Käyttökelpoisuus</b>
<select name="Käyttökelpoisuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei käyttökelpoinen">Ei käyttökelpoinen</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<br />
Haku: <input type="text" name="text" />
<input type="submit" value="Hae" />
</form>
I haven't used PHP to contact database before so the PHP code is very messy.
I don't understand any more than the very basics from PHP, I haven't used variables or objects or anything complex before.
HTML form:
variable1
variable2
variable3
variable4
variable5
--->
PHP script:
select * from db
where variable1 and variable2 and variable3 and variable4
--->
display results matching the criteria
Current code causes this error message in error_log:
PHP Warning: mysqli::query(): Empty query in /home/user/public_html/folder/script.php on line 23
I have already tried over 15 different variations of variables and sql query in total and nothing has worked..
If we shorten your if (isset($_POST ... something you can clearly see. This instruction
$results = $conn->query($query);
is always executed, regardless of whether isset returns true or not.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
}
$results = $conn->query($query);
So if only one field has not been filled out correctly, the error is always the same :
PHP Warning: mysqli::query(): Empty query in ....
This makes it difficult to determine where the fault really comes from.
Place the curly bracket } behind database logic.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
....
}
}
?>
create a short test program to test only the database. Set only really necessary data fields in the query
test.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$Kohderyhmä = "KohderyTest"; // replace with really existing values
$query = "SELECT * FROM `tietokanta` WHERE Kohderyhmä='".$Kohderyhmä."' ";
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
$results->free();
?>
Add hardcoded variables $Näytön_aste = "reallyExistingValue"; , add query data field for data field and watch when it starts to stutter.
Also we can not see your function get_post()
If you mean the Wordpress function get_post(), your call to the function is wrong.
I can well imagine that the failure from the function get_post() comes.
And you always false or empty values assigns.
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
assign it direct.
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
...)
{
$Kohderyhmä = $post['Kohderyhmä'];
...
Also you are using all select fields from the <form>, in the query.
4 Select's with 8,6,6,6 options means
8x6x6x6 == 1728
1728 possibilities are you shure you have one datarecord where all values matches.
WHERE Ko...='$Ko...' AND `Näy...`='$Näy...' AND `Vai...`='$Vai...' AND `Käy...`='$Käy...'";
WHERE All four Datafields must match to get a result !!!!!!!!!!!!!
You have to find a combination where all four values simultaneously exist.
UPDATE
OP new question :
If you want empty or some named values stop searching for a value in
database.
required every single variable to be found in the database which it
didn't find because I couldn't set the variable and there is no value
for "Kaikki" in the database, the word "Kaikki" means all choices
below that choice in the HTML form and for that I need some PHP
Here comes the new test.php
1) don't do $post['Näytön aste']; In the form the name is
<select name="Näytön aste" style="...">.
This will translated by submit to
$post['Näytön_aste']; look at the underscore _
This must be done with all select name with spaces in the name !!
2) That was the reason why you get not all $_POST[....] values !
OK ?
3) replace in your form
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
with
<form action="testNew.php" method="POST">
testNew.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
} else { die ("No valid values"); }
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Kohderyhmä`= '".$Kohderyhmä."'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste`= '".$Näytön_aste."'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus`= '".$Vaikutusten_vahvuus."'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus: luokka`= '".$Käyttökelpoisuus."'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
} else {
echo "with your choices no records were found";
}
$results->free();
?>
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='{$Kohderyhmä}' AND `Näytön aste`='{$Näytön_aste}' AND `Vaikutusten vahvuus`='{$Vaikutusten_vahvuus}' AND `Käyttökelpoisuus: luokka`='{$Käyttökelpoisuus}'";
Replace your query with this, and try.

Insert values array of php checkboxes to mysql

I have many checkboxes that should send two values to MySQL. However, I'm not getting the right value.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($rootWord != "") {
$tag = "janaan";
$imbuhan = array();
// Imbuhan Kata Nama
$result_awalan_ke = awalan_ke($rootWord, $tag);
$imbuhan[1] = array('imbuhan' => $result_awalan_ke[0], 'pos' => $result_awalan_ke[2]);
$resultDummy = mysql_query("SELECT * FROM tabletruefalse WHERE rootWord ='$result_awalan_ke[0]'");
$exist = mysql_fetch_array($resultDummy, MYSQL_BOTH);
if ($exist) {
echo '<tr><td>'.$result_awalan_ke[1] .' : '. $result_awalan_ke[0] . '</td><td>'. $result_awalan_ke[2].'</td><td>&nbsp&nbsp&nbsp&nbsp<input type="checkbox" name="imbuhan[]" value="1" /></td></tr></br>';
}
$result_awalan_pe = awalan_pe($rootWord, $tag);
$imbuhan[2] = array('imbuhan' => $result_awalan_pe[0], 'pos' => $result_awalan_pe[2]);
$resultDummy = mysql_query("SELECT * FROM tabletruefalse WHERE rootWord ='$result_awalan_pe[0]'");
$exist = mysql_fetch_array($resultDummy, MYSQL_BOTH);
if ($exist) {
echo '<tr><td>'.$result_awalan_pe[1] .' : '. $result_awalan_pe[0] . '</td><td>'. $result_awalan_pe[2].'</td><td>&nbsp&nbsp&nbsp&nbsp<input type="checkbox" name="imbuhan[]" value="2" /></td></tr></br>';
}
?>
Instead I got the value of checkboxes. E.g. 1 or 2.
Below is the insert to MySQL code:
<?php
if(isset($_POST['imbuhan'])){
foreach($_POST['imbuhan'] as $value){
$insert = mysql_query("INSERT INTO tablebyuser(rootWord, posWord)
VALUES ('$value[imbuhan]', '$value[pos]')");
}
}
?>

PHP Foreach loop problem with mySQL INSERT INTO

I am having a big issue.
This is the first time I sue a foreach and I do not even know if it's the right thing to use.
I have a textarea where my members can add some text.
They also have all the accounts where to send the posted text.
Accounts are of two types F and T.
They are shown as checkboxes.
So when a member types "submit" the text should be INSERTED in a specific table for EACH of the selected accounts. I thought php foreach was the right thing. But I am not sure anymore.
Please take in mind I do not know anything about foreach and arrays. So please when helping me, consider to provide the modded code =D . Thank you so much!
<?php
require_once('dbconnection.php');
$MembID = (int)$_COOKIE['Loggedin'];
?>
<form action="" method="post">
<p align="center"><textarea id="countable1" name="addit" cols="48" rows="10" style="border-color: #ccc; border-style: solid;"></textarea>
<br>
<?
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$on="on";
$queryF ="SELECT * FROM `TableF` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryF) or die("Errore select from TableF: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "F" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="f[<?php echo $rowid?>]" <?php echo $checkit;?>>
</div>
<?
}//END WHILE MYSQL
}else{
echo "you do not have any Active account";
}
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryTW ="SELECT * FROM `TableT` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryTW) or die("Errore select TableT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "T" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="t[<?php echo $rowid?>]" <?php echo $checkit;?> >
</div>
<?
}//END 2° WHILE MYSQL
}else{
echo "you do not have any Active account";
}
?>
<input type="submit" value="submit">
</form>
<?
//WHEN CHECKBOXES "F" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "F" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['f'])){
$thispostF = $_POST['f'];
$f="F";
foreach ($thispostF as $valF)
//THE MOST IMPORTANT FIELD HERE IS "Type". THE ARRAY INSERT "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddF="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$f."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
//WHEN CHECKBOXES "T" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "T" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['t'])){
$thispostT = $_POST['t'];
$t="T";
foreach ($thispostT as $valF)
//THE MOST IMPORTANT VALUE HERE IS "Type". THE ARRAY GIVES "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
?>
foreach ($thispostT as $valF)
{
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
please put start and ending bracket to your foreach loop and try i have not read the whole code but just found you missing the brackets. hope that helps you.
I think I know what you're doing...
You're going to need to do:
foreach($_POST as $key => $value) {
$type = substr($key,0,1);
$id = substr($key,1);
if($type == 't') {
// do insert for t table here
} else if($type == 'f') {
// do insert for f table here
}
}
I didn't test it but it should be something like this.
My suggestion is
create field name as t[] (array)
onchecked value will be passed on the next page
the form checkbox field should be like that
<input type="checkbox" name="t[]" value="< ?php echo $rowid?>" <?php echo $checkit;? > >
and when you Submit the form
GET THE VALUE and insert in to database;
< ?
if($_POST['t'])
{
foreach($_POST['t'] as $v)
{
queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
}
? >

Categories