This is my first 'built from the ground up' PHP/MySQL project. I've built a very simple HTML form with the same row repeated multiple times:
<h2 style="margin-top:0">Current Projects</h2>
Project: <input name="project1" type="text" size="40" value="1" />
Status: <input name="status1" type="text" size="40" value="1" />
Estimated Completion: <input name="estCompletion1" type="text" size="12" value="1" /><br />
Project: <input name="project2" type="text" size="40" value="2" />
Status: <input name="status2" type="text" size="40" value="2" />
Estimated Completion: <input name="estCompletion2" type="text" size="12" value="2" /><br />
Project: <input name="project3" type="text" size="40" value="3" />
Status: <input name="status3" type="text" size="40" value="3" />
Estimated Completion: <input name="estCompletion3" type="text" size="12" value="3" /><br />
I'm trying to write all of these to the same database table at the same time, but on different rows.
$sql = "INSERT INTO current_project (date, est_completion, project_name, status)
VALUES (NOW(), '$estCompletion1', '$project1', '$status1'),
(NOW(), '$estCompletion2', '$project2', '$status2'),
(NOW(), '$estCompletion3', '$project3', '$status3')";
The problem with doing it like this is that it inserts the data from the variable, even if it's null. So if the user only enters data in the first row of fields (project1, status1, etc.) the other 2 insert an empty row.
Is there a way, maybe using 'if isset()', so that I don't have any blank fields in my database?
Build SQL dynamically.
Something like this:
$inserts = Array();
for($i=1; $i<=3; $i++) {
if (!$_POST["project".$i] && !$_POST["status".$i] && !$_POST["estCompletion".$i]) continue;
$inserts[] = "(NOW(), '".$_POST["estCompletion".$i]."', '".$_POST["project".$i]."', '".$_POST["status".$i]."')";
}
if (Count($inserts)>0) {
$sql = "INSERT INTO current_project (date, est_completion, project_name, status)
VALUES (" . implode("), (", $inserts) . ")";
}
At this point $sql should have full SQL query only with those rows where all three fields were submitted.
If you want to check the value of posted variable is null, always use empty() method.
For more information: Visit php.net
for($i=1; $i<=3; $i++) {
$estCompletion= $_POST["estCompletion".$i];
$project= $_POST["project".$i];
$status= $_POST["status".$i];
if (!empty($estCompletion) && !empty($project) && !empty($status))
{
$sql = "INSERT INTO current_project (date, est_completion, project_name, status) VALUES (NOW(), '".$estCompletion."', '".$project."', '".$status."')";
}
unset($estCompletion, $project, $status);
}
Related
I have searched everywhere and still cannot find the answer. Can anybody help?
I have a PHP form that consists of a textbox (with data that will go into column name_id) and a checkbox, that has the option to go to 5 different MySQL tables:
'table A'
'table B'
'table C'
'table D'
'table E'
People can choose which table they want, and the name_id will go to the tables selected.
How can I do this?
my Answere in different from #RandD-SexyBoy- . my sql query is different from #RandD-SexyBoy- he has used $sql = "INSERT INTO $tables[$i](nameID_column); with out VALUES (:nameID_column)
were is have used $sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)"
Here are 3 cases the user responds
case first : user may select a single table
case second : user may select multiple tables. here we must use foreach() loop and dynamic sql queries.
case third : user may not select any table in this case we must give user a message table not selected
html form :
`
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name_id" required>
<p>select your table to add data</p>
<input type="checkbox" name="tables[]" value="tblA">Table A<br>
<input type="checkbox" name="tables[]" value="tblB">Table B<br>
<input type="checkbox" name="tables[]" value="tblC">Table C<br>
<input type="checkbox" name="tables[]" value="tblD">Table D<br>
<input type="checkbox" name="tables[]" value="tblE">Table E<br>
<input type="submit" name="submit">
</form>
</body>
</html>
`
php file :
<?php
$con = new mysqli('localhost','root','admin','demo');
if(!$con){
die("Connection ".$con->connect_error);
}
if(isset($_POST['submit'])){
$name_id = $_POST['name_id'];
$tables = $_POST['tables'];
if(!empty($tables)){
foreach($tables as $key=>$v){
$sql = $con->stmt_init();
if($sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)")){
$sql->bind_param($name_id);
$sql->execute();
echo "DATA INSERTED";
}
else
{
echo "Error".$con->error;
}
}
}
else
{
echo "You have not selected tables";
}
}
?>
So one naive approach could be, when the user submits the form, on your php side, you check which checkboxes are ticked and your condition could be something like this
if(checkbox_for_table_A) {// insert query}
if(checkbox_for_table_B) {// insert query}
if(checkbox_for_table_C) {// insert query}
if(checkbox_for_table_D) {// insert query}
if(checkbox_for_table_E) {// insert query}
This way if one checkbox is selected it will save into that table, if more than one tables are selected, it will go in that table.
Hope this helps! Ask any doubt you get in the comment section.
Adapting from sources : post checkbox value and tutorial http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/, you can use this approach :
HTML Form :
<form action="checkbox-form.php" method="post">
<input type="text" name="name_id" /><br />
Select your database: <br/>
<input type="checkbox" name="formTables[]" value="A" />Table A<br />
<input type="checkbox" name="formTables[]" value="B" />Table B<br />
<input type="checkbox" name="formTables[]" value="C" />Table C<br />
<input type="checkbox" name="formTables[]" value="D" />Table D<br />
<input type="checkbox" name="formTables[]" value="E" />Table E<br />
<input type="submit" name="formSubmit" value="Submit" />
</form>
Now the PHP script :
<?php
$pdo_connection = new PDO('mysql:host=localhost;dbname=test', 'demouser', 'demopass');
$tables = $_POST['formTables'];
if(empty($tables))
{
echo("You didn't select any tables.");
}
else
{
$N = count($tables);
echo("You selected $N table(s): ");
for($i=0; $i < $N; $i++)
{
$sql = "INSERT INTO $tables[$i](nameID_column);
$stmt = $pdo_connection->prepare($sql);
$stmt->bindParam(':nameID_column', $_POST['name_id'], PDO::PARAM_STR);
$stmt->execute();
echo("Your ID Name was inserted into table $tables[$i] ! <br /> ");
}
}
?>
I have these checkboxes that I am trying to (ultimately concat two together and) insert into a database. I've tried several ways and have searched through many pages, but my page keeps breaking when I try to insert. I'm not actually getting an error in my apache log, but a message is triggered that makes me believe it's some kind of sql error (the else statement at the end, which is a check if the query affected any rows). The error isn't thrown until I add the foreach and additional awards to the query .
Here is the form section
<label><input type="checkbox" name="check_list[]" Value = "Castle Connolly Top U.S. Doctor" />Castle Connolly Top U.S. Doctor</label>
<!-- <input type="text" name="check_year" value="<php echo decode_text($check_year);?>"/> -->
<label><input type="checkbox" name="check_list[]" Value = "Vitals Patients Choice"/>Vitals Patient's Choice</label>
<!--<input type="text" name="check_year" value="<php echo decode_text($check_year);?>"/> -->
<label><input type="checkbox" name="check_list[]" Value = "Vitals Compassionate Doctor"/>Vital's Compassionate Doctor Recognition</label>
<!--<input type="text" name="check_year" value="<php echo decode_text($check_year);?>"/> -->
<label><input type="checkbox" name="check_list[]" Value = "Super Doctor"/>Super Doctor</label>
<!--<input type="text" name="check_year" value <php echo decode_text($check_year);?>"/> -->
inserting
$additional_awards = '';
$check_list = $_POST['check_list'];
foreach($check_list as $check)
{
$additional_awards .= $check.", ";
}
// insert new user
$sql = 'INSERT INTO docflight_doctors (
email,
user_name,
user_password,
additional_awards,
preferred_language,
date_created,
registered_from_ip,
last_logged_ip,
is_active,
is_removed,
comments,
registration_code )
VALUES(
\''.encode_text($email).'\',
\''.encode_text($user_name).'\',
\''.$user_password.'\',
\''.$additional_awards.'\',
\''.Application::Get('lang').'\',
\''.date('Y-m-d H:i:s').'\',
\''.$user_ip.'\',
\'\',
'.$is_active.',
0,
\'\',
\''.$registration_code.'\')';
if(database_void_query($sql) > 0){
/// do other stuff
else{
///echo mysql_error();
$msg = draw_important_message(_CREATING_ACCOUNT_ERROR, false);
FIXED, \''.$user_password.'\', should have been '.$user_password.', for some reason ....
on page 1 i have a form, then on page 2 which is the processor file, i want to select records based on the checked checkboxes that were checked on page 1.
<form action="output.php" method="post">
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="something else" />
<input type="checkbox" id="" class="" name="check_list[]" value="yet another thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="some name" />
<input type="checkbox" id="" class="" name="check_list[]" value="some other name" />
<input type="submit" value="Submit" name="submit">
</form>
the following foreach can display all the values of everything that was checked, but i don't know how to take it further into my sql select statement to select all the records that have a column field by that name.
foreach($_POST['check_list'] as $check) {
echo $check . '<br>';
}
lets say in a table called stuff there are these fields
id, first_title, second_title
so i want to do the following, but obviously this isn't the way to write it. this is the part i need help with.
SELECT * FROM stuff WHERE first_title = $check or second_title = $check
lets us further say that these records exist in the table...
id first_title second_title
-----------------------------------------
1 something something else
2 yet another thing one more thing
3 some name some other name
then lets say these checkboxes were checked:
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
so what i want to happen is for my select statement to select record 1 and record 2 and not record 3, because "something" is in the first_title column of the first record, and "one more thing" is in the second_title of the second record, and nothing was checked that is in third record.
i hope i gave as much detail as is needed. let me know if you need further explanation.
Use the SQL IN operator to test if a column is in a list of values. Here's how to write it with MySQLI:
$in_str = implode(', ', array_map(function($title) use ($con) {
return "'" . $con->real_escape_string($title) . "'";
}, $_POST['check_list']));
$sql = "SELECT * FROM stuff WHERE first_title IN ($in_str) OR second_title IN ($in_str)";
$result = $con->query($sql);
try this dynamic where condition in your code
<?php
$arr_where = array();
foreach($_POST['check_list'] as $check) {
$arr_where[] = " first_name='$check' OR last_name='$check' ";
}
$where_text = implode("OR", $arr_where);
$sql = "SELECT * FROM stuff WHERE ".$where_text;
?>
I have an HTML input form that is being sent as a PHP_SELF and then stored on a MySQL table. The input field is dynamically controlled with JS. There are 4 inputs: number (text), amount (int), Approval (text), and Date (text). There inputs are all arrays when they are sent to the PHP file via POST. They're stored in a MySQL table with column fields as: ID (primary key), num (text(4)), amnt (decimal(8,2)), app (text(10)), and date (varchar(10)). I'm getting three significant errors when I try to run the page.
If a number such a 0125 is entered in the number field on the form, it is stored as 125 in the MySQL table. This is regardless of the fact that the field is being stored as a text string.
The Approval field works perfectly fine when only integers are entered, however, when only text or a combination of text and numbers is inserted, the MySQL query produces the following error: Error: Unknown column 'aft859' in 'field list'. For example, when 853234 is entered, everything goes through fine, but when aft859 is entered, the error is produced.
When a date is entered, it gets inputted into the MySQL table as a decimal value. For example, a date of 08/07/2012 is saved as '0.00056802'.
I have checked every line to make sure that nothing is being converted in the PHP or HTML process, and I've echoed every line to make sure that the values are being handled properly. After much debugging, I'm lead to believe that the following two sections might be causing my problem:
//Check To See If User Has Already Created Table
$sql = "CREATE TABLE IF NOT EXISTS $tablename_cc (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
cc_num TEXT(4),
cc_amnt DECIMAL(8,2),
cc_app TEXT(10),
cc_date VARCHAR(10)
);";
or it might be this:
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
die('Error: ' . mysql_error());
else
echo '<strong>', "Your information have been submitted and will be added to your account upon approval.", '</strong>', "</br>", "</br>", "</br>";
I'm not too familiar with PHP, HTML, or MySQL (this is my first program ever), and I'm not sure if I've missed something. I tried to check all quotes and make sure they were right. I'm running all this in Wordpress, just in case that's culprit. Here is my code in its entirety for reference:
<?php
if(isset($_POST['submit']))
{
//Get Current User Login
global $current_user;
$current_user = wp_get_current_user();
$ulog = $current_user->user_login;
$tablename_cc = "cc_".$ulog;
//Check To See If User Has Already Created Table
$sql = "CREATE TABLE IF NOT EXISTS $tablename_cc (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
cc_num TEXT(4),
cc_amnt DECIMAL(8,2),
cc_app TEXT(10),
cc_date VARCHAR(10)
);";
mysql_query($sql);
$cc_num = $_POST['cc_num'];
$cc_amnt = $_POST['cc_amnt'];
$cc_app = $_POST['cc_app'];
$cc_date = $_POST['cc_date'];
$items = array_map(null,$cc_num,$cc_amnt,$cc_app,$cc_date);
$pairs = array();
foreach ($items as $sub) {
if(implode(',', $sub) != ",,,")
$pairs[] = '('.implode(',', $sub).')';
}
echo implode(',',$pairs);
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
die('Error: ' . mysql_error());
else
echo '<strong>', "Your information has been submitted and will be added to your account upon approval.", '</strong>', "</br>", "</br>", "</br>";
}
?>
<!--raw-->
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
$("*#date").mask("99/99/9999");
// business rule: you can only add 20 names
if (newNum == 20)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$("*#date").mask("99/99/9999");
});
</script>
</head>
<body>
Please fill in your information in the form below and press submit. If you need to add more, please click the "Add" button at the bottom of the form. You may enter a maximum of 20 at a time. Leave all unused fields blank.
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Information:</legend>
<div id="input1" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input2" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input3" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input4" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div id="input5" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="cc_num[]" maxlength="4" size="4" /> CC Amount: <input id="camnt" type="int" name="cc_amnt[]" /> Approval Code: <input id="appr" type="text" name="cc_app[]" maxlength="10" size="10" /> Date: <input id="date" type="text" name="cc_date[]" /> </br>
</div>
<div>
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
</fieldset>
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
<!--/raw-->
The reason your text values are being truncated (losing leading zeros) is because you're inserting them as numbers and MySQL is dropping the leading zero, and the dates are becoming decimals is because you're inserting them as equations and MySQL is evaluating them.
The reason for this is this line:
$pairs[] = '('.implode(',', $sub).')';
None of the values are surrounded by quotes. You can fix this with:
$pairs = '("'.implode('","', $sub).'")';
Then, you're using implode() again on the already imploded list on the line:
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
Update this line to:
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES ' .$pairs . ))
if (!mysql_query('INSERT INTO ' .$tablename_cc. '(cc_num, cc_amnt, cc_app, cc_date) VALUES '.implode(',',$pairs)))
You need to wrap the input values in apostrophes; otherwise, they'll be treated as numbers - that's why you get the Unknown column error and the date is treated as a sum and not a date.
if (!mysql_query("INSERT INTO " .$tablename_cc. " (cc_num, cc_amnt, cc_app, cc_date) VALUES '".implode("','",$pairs) . "'"))
I think that will do it.
I have a page which basically allows an admin user to create manager user types (basically a register function. So when the values are submitted, they are stored into the DB, very very basic stuff. However, I have a hidden variable type..reasons are I have 3 different user levels and I have declared they identification as an integer (e.g. 7 = manager, 8 =user etc.)
Can someone help me out with how to correctly pass this hidden value so it stores in the database...
Here is my form:
<form id="userreg" name="userreg" method="post" action="adduser-process.php">
<label>Full Name:</label> <input name="fullname" size="40" id="fullname" value="<?php if (isset($_POST['fullname'])); ?>"/>
<br />
<label>Username:</label> <input name="username" size="40" id="username" value="<?php if (isset($_POST['username'])); ?>"/> <br />
<label>Password:</label> <input name="password" size="40" id="password" value="<?php if (isset($_POST['password'])); ?>"/> <br />
<label>Email Address:</label> <input name="emailaddress" size="40" id="emailaddress" value="<?php if (isset($_POST['emailaddress'])); ?>"/>
<br />
<input name="userlevel" type="hidden" size="1" id="userlevel" value="<?php $_POST[5]; ?>" /> <br />
<input value="Add User" class="addbtn" type="submit" />
</form></div>
Next, here is the script that runs the query:
<?php
require_once "config.php";
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$password = $_POST['password'];
$emailaddress = $_POST['emailaddress'];
$userlevel = $_POST[5];
$sql = "INSERT INTO users_tb VALUES('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".$emailaddress."','".$userlevel."')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: administratorfrontview.php");
exit();
?>
I'm basically trying to pass the hidden typem with a constant value of '5' just for this form, as it will not be changed...also while im here, for some reason, the 'fullname' is not stored in the DB either!!?? WTH?? all other fields are processed fine. Any help is much appreciated! Thank you.
Two things. One, $userlevel should equal $_POST['userlevel'] not 5 as POST data isn't always in that order. Two, your insert statement should be preceded with the column names (to prevent any data from going in the wrong order).
$sql = "INSERT INFO users_tb (id, name, username, password, email, userlevel) ".
"('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".
$emailaddress."','".$userlevel."')";
Your PHP for outputting the value is wrong. Use:
<?= $_POST[5]; ?>
or
<?php echo $_POST[5]; ?>