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>    <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>    <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]')");
}
}
?>
Related
how can i brief this queries?
i want to combine them but get specific error alert and different three variable
<?php
$sql = "SELECT content FROM post where title='tv'";
$sql2 = "SELECT content FROM post where title='radio'";
$sql3 = "SELECT content FROM post where title='net'";
$result = $connection->query($sql);
$result2 = $connection->query($sql2);
$result3 = $connection->query($sql3);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tvPrice = $row['content'];
}
}else{
echo "tv error";
}
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$radioPrice = $row['content'];
}
}else{
echo "radio error";
}
if ($result3->num_rows > 0) {
while($row = $result3->fetch_assoc()) {
$netPrice = $row['content'];
}
}else{
echo "net error";
}
?>
Using the IN() you can return only those rows with a title of 'tv', 'radio' and 'net'. Then add the title to the query selection so you know which results a re which.
Then just amend you code to fetch all the results into a rows array and then check for the entries and report errors accordingly
<?php
// make a connection to the database obviously :)
$sql = "SELECT title, content
FROM post
WHERE title IN('tv', 'radio', 'net')";
$result = $connection->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
// better initialise the variables in case you try using them later
$tvPrice = $radioPrice = $netPrice = 0;
foreach ($rows as $row){
if ($row['title'] == 'tv')){
$tvPrice = $row['content'];
}
if ($row['title'] == 'radio') {
$radioPrice = $row['content'];
}
if ($row['title'] == 'net') {
$netPrice = $row['content'];
}
}
if ( $tvPrice == 0 ) echo 'tv error';
if ( $radioPrice == 0 ) echo 'radio error';
if ( $netPrice == 0 ) echo 'net error';
?>
Usually you don't actually need tree (or more) variables; use an array.
<?php
$titles = ['tv', 'radio', 'net'];
// Generate the query
$sql =
"SELECT content, title FROM post WHERE title IN("
. implode(", ", array_map(function( $title ) use( $connection ) {
return '"' . mysqli_real_escape_string($connection, $title) . '"';
}, $titles) )
. ")";
$result = $connection->query($sql);
$prices = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Check for duplicates
if( !empty( $prices[ $row['title'] . 'Price' ] ) )
echo $row['title'] . " has duplicate error";
else
$prices[ $row['title'] . 'Price' ] = $row['content'];
}
}
// Check if we have all desires rows
foreach( $titles as $title )
if( empty( $prices[ $title . 'Price' ] ) )
echo "$title missing error";
// If you really need tree variables instead of array:
extract($prices);
Here is my code to add multiple types to table. I want to combine areas, location, types and add them in the table at once. I think this just wont work if(!empty($_POST['types'] && $_POST[''] && $_POST[''] ) Thanks!
if(!empty($_POST['types'])) {
$values = array();
foreach($_POST['types'] as $typ_id) {
$values[] = sprintf('(%d, %d)', $station_id, $typ_id);
}
$query = 'INSERT IGNORE INTO station_typ_tab
(station_id, typ_id, area_id, location_id)
VALUES ' .
implode(',', $values);
mysql_query($query, $db) or die(mysql_error($db));
}
EDIT: here is part of code for types[] and same is for areas and location
<td>Types:<br/> <small>CTRL + click to set multiple pollutants</em></small>
</td>
<td>
<?php
$query = 'SELECT typ_id, typ FROM typ_tab ORDER BY typ ASC';
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
echo '<select multiple name="types[]">';
while ($row = mysql_fetch_array($result)) {
if (isset($station_typ[$row['typ_id']])) {
echo '<option value="' . $row['typ_id'] . '"
selected="selected">';
} else {
echo '<option value="' . $row['typ_id'] .'">';
}
echo $row['typ'] . '</option>';
}
echo '</selected>';
} else {
echo '<p><strong>Databaza je prazdna... Enter database</strong></p>';
}
mysql_free_result($result);
how to combine $_POST for types, location and areas if they comes from different selecting input. something like if(!empty($_POST['types'] && $_POST['areas'] && $_POST['location']) ){ $values = array(); foreach( NEW VARIABLE as $typ_id && area_id &&location_id) { $values[] = sprintf('(%d, %d, %d, %d)', $station_id, $typ_id, area_id, location_id); if it is possible to do it like this
to combine in IF try to use
if((!empty($_POST['types'])) && (!empty($_POST['area'])) && (!$_POST['location'])));
I'm using checkbox buttons for updating occupation of day in month in my calendar.
If I check just one checkbox it updates it, but if I check multiple checkboxes it doesn't update any row.
Here is my code:
$query = mysqli_query($con, "SELECT * FROM koledar");
while ($vsidnevi = mysqli_fetch_assoc($query)) {
$dnevi = [$vsidnevi['dan']];
foreach ($dnevi as $dan) {
if ($vsidnevi['zasedenost']==0) {
echo '<label class="btn btn-primary">';
echo '<input type="checkbox" name="miha" value="' . $dan . '" data-toggle="button">' . $dan;
echo '</label>';
} elseif ($vsidnevi['zasedenost']==1) {
echo '<label class="btn btn-primary active disabled">';
echo '<input type="checkbox" name="miha" value="' . $dan . '" data-toggle="button">' . $dan;
echo '</label>';
}
}
}
and
if (isset($_GET['dodaj']) && $_GET['dodaj']=="true") {
if(isset($_POST['miha'])) {
$daen = $_POST['miha'];
$dodaj = mysqli_query($con, "UPDATE koledar SET zasedenost=1 WHERE dan=" . $daen . "");
}
}
Firstly, you should be passing your literal values to MySQL as parameters to a prepared statement (in order to defeat SQL injection attacks).
When multiple values are submitted, $_POST['miha'] will be an array over which you must loop:
if (isset($_GET['dodaj']) && $_GET['dodaj']=="true") {
if(isset($_POST['miha'])) {
$dodaj = mysqli_prepare($con, '
UPDATE koledar
SET zasedenost=1
WHERE dan=?
');
mysqli_stmt_bind_param($dodaj, 's', $daen);
foreach ($_POST['miha'] as $daen) {
mysqli_stmt_execute($dodaj);
}
}
}
Or else use IN ():
if (isset($_GET['dodaj']) && $_GET['dodaj']=="true") {
if(isset($_POST['miha'])) {
$inq = implode(',', array_fill(0, count($_POST['miha']), '?'));
$dodaj = mysqli_prepare($con, "
UPDATE koledar
SET zasedenost=1
WHERE dan IN ($inq)
");
call_user_func_array('mysqli_stmt_bind_param', array_merge(
array(
$dodaj,
str_repeat('s', count($_POST['miha']))
),
$_POST['miha']
));
mysqli_stmt_execute($dodaj);
}
}
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();
}
?>
I am having problem adding up the values in a column with php.
These values where sent from checkboxes and i want to count only the values that where checked from the unit column.
Here is my code:
<?php
$id = $_POST['course'];
foreach($id as $value)
{
//echo $value;
$query = " SELECT * FROM french WHERE id= $value ";
$result = mysql_query($query) or die('Error, query failed');
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$unit = $row['unit'];
$status = $row['status'];
?>
Are you trying like this? Getting form array of form checkboxs and checking on database via ID's?
HTML FORM
Check 1 <input type="checkbox" name="val[]" />
Check 2 <input type="checkbox" name="val[]" />
PHP RESULT
$val = $_POST['val'];
$count = count($val);
foreach ($val as $val_res)
{
$query = 'SELECT * FROM french WHERE id='.$val_res;
}