I have tried many different solutions to no avail you will see the attempts.
The columns in question are tinyint 1 pass and 0 fail. From poweradapter down. The textarea goes into the database just fine. I've tried enumerating the boolean and print_r($_POST and now im just lost.
*Also put through mysqli_real_escape
if (isset($_POST['submit'])) {
$tester = $_POST['tester'];
$manufacturer = $_POST['manufacturer'];
$model = $_POST['model'];
$serial = $_POST['serial'];
$poweradapter = $_POST['poweradapter'];
$query = "INSERT INTO tested (tester, manufacturer, model, serial, poweradapter)
VALUES ('$tester','$manufacturer','$model','$serial','$poweradapter');";
<div class="fb-radio-group form-group field-poweradapter"><label for="poweradapter" class="fb-radio-group-label">Power Adapter<span class="fb-required">*</span><span class="tooltip-element" tooltip="Plug into Laptop - Charges the Battery">?</span></label>
<div class="radio-group"><div class="radio"><label for="poweradapter-0"><input name="poweradapter" id="poweradapter-0" required="required" aria-required="true" value="1" type="radio">Pass</label></div>
<div class="radio"><label for="poweradapter-1"><input name="poweradapter" id="poweradapter-1" required="required" aria-required="true" value="0" type="radio">Fail</label></div>
</div></div>
Unless MariaDB works quite a bit differently than regular MySQL, it looks to me like you are only storing a MySQL statement in a variable without actually executing it.
You may want to do something like:
$query = $db->query("INSERT INTO tested (tester, manufacturer, model, serial, poweradapter)
VALUES ('$tester','$manufacturer','$model','$serial','$poweradapter')";
With $db containing your database connection.
So I suppose I'll just rewrite the form as the issue isn't the radio button entirely rather when I mix one of the textareas with it. Thank you all
Related
Just wondering if anyone can point out where I'm going wrong with the code below. I'm trying to gather the text from the form and UPDATE a field within the database with the text.
I have tested the SQL statement alone and it is updating the column correctly, but seems to be an issue with the PHP syntax as when i click on the submit button, it only insets '1' into the columns.
PHP:
$SubmitComments = isset($_POST['SubmitComments']);
$AddComment = isset($_POST['AddComment']);
if ($SubmitComments){
mysql_query ("UPDATE `table` SET `column` = '$AddComment' WHERE `column` = '$.....'") or die(mysql_error());
echo 'Comment added';
}
HTML:
<tr>
<td>Add Comment</td>
<td align="center"><form name="form1" method="POST" action=""><input name="AddComment" type="text" id="AddComment" autocomplete="off" placeholder="Add comments..." size="45px"><br />
<input type="submit" name="SubmitComments" id="SubmitComments" value="Submit"></form></td>
</tr>
Right, from the top. isset returns a bool, so $SubmitComments would only equal true or false, it will never equal the POST variable (Same with $AddComment). Consider instead:
if(isset($_POST['SubmitComments'])&&isset($_POST['AddComment']))
{
$SubmitComments = $_POST['SubmitComments'];
$AddComment = $_POST['AddComment'];
//Rest of Code
}
Second, table and column names do not need single quotes around them. And finally, as addressed in the comments, think about using MySQLi instead as if your script does eventually work, one malformed comment will erase your entire database.
Example:
If their comment is even just butts';-- It will make the SQL:
UPDATE table SET column = 'butts';--' WHERE column = '$.....'
Which is the equivalent of:
UPDATE table SET column = 'butts';
Making all of your comments just the word "butts", and that's just a humorously childish attack, compared to stealing usernames/passwords, trashing the database etc
I'm trying to update a table of dishes with a new entry and cross reference it to an existing table of ingredients. For each dish added, the user is required to assign existing ingredients and the volume required on multiple lines. On submission, the Dish should be entered into the table 'Dishes' and the assigned ingredients should be entered into the 'DishIng' linked tabled.
My tables are set like this:
Table: "Dishes" Columns: DishID, DishName, Serves, etc...
Table: "DishIng" Columns: DishID, IngID, Volume
Table: "Ingredients" Columns: IngID, IngName, Packsize etc...
HTML:
DishID:
Name:
Catagory :
Serving:
SRP:
Method :
Source :
IngID:
Volume:
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
</ul>
<input type="submit">
</form>
Any suggestions for dymanically adding a row of ingredients in HTML would be very welcome.
PHP:
<?php
require_once('db_connect.php');
$DishID = mysqli_real_escape_string($con, $_POST['DishID']);
$DishName = mysqli_real_escape_string($con, $_POST['DishName']);
$DishCatID = mysqli_real_escape_string($con, $_POST['DishCatID']);
$Serving = mysqli_real_escape_string($con, $_POST['Serving']);
$SRP = mysqli_real_escape_string($con, $_POST['SRP']);
$Method = mysqli_real_escape_string($con, $_POST['Method']);
$SourceID = mysqli_real_escape_string($con, $_POST['SourceID']);
$IngID = mysqli_real_escape_string($con, $_POST['IngID']);
$Volume = mysqli_real_escape_string($con, $_POST['Volume']);
$array = array('$DishID', '$IngID', '$Volume');
$sql="INSERT INTO Dishes (DishID, DishName, DishCatID, Serving, SRP, Method, SourceID)
VALUES ('$DishID', '$DishName', '$DishCatID', '$Serving', '$SRP', '$Method', '$SourceID')";
$sql2 = "INSERT INTO DishIng (DishID, IngID, Volume) VALUES ('$DishID', '$IngID', '$Volume')";
$it = new ArrayIterator ( $array );
$cit = new CachingIterator ( $it );
foreach ($cit as $value)
{
$sql2 .= "('".$cit->key()."','" .$cit->current()."')";
if( $cit->hasNext() )
{
$sql2 .= ",";
}
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con));
}
echo "records added";
require_once('db_disconnect.php');
php?>
Currently on submit, it only updates the 'Dishes' table and gives me this message: '1 record addedError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('0','$DishID'),('1','$IngID'),('2','$Volume')' at line 1'
A high level of how you do this (although there are plenty of ways, this is just one with straight DB/PHP/HTML):
Your php will create a form to input the dish fields from the user.
Your php will then pull all of the ingredients from the ingredient table for that dish
Your php will iterate through the results returned from that query and for each result will:
Create a checkbox type input for the ingredient, and
Create a Text field type input for the ingredient and.
Create a Hidden field with the IngID
Once the user submits the form:
Your php will insert the to the dish table based on the dish fields on the form submitted.
Your php will iterate through the ingredients fields from the form submission and with each one will:
Determine if that ingredients checkbox is checked. If it is it will:
Insert into the DishIng table using the Hidden IngID field and the Volume field
Essentially, there is are two FOR loops. One to loop through the initial list of ingredients to make your form, and a second to loop through the form that is submitted. Each ingredient with a check mark will need it's own SQL INSERT statement to be added into the DishIng table.
How to iterate through SQL results in php: Iterate through Mysql Rows in PHP
How to iterate through Form fields in php: PHP loop through array of HTML textboxes
Because you are taking in user input and sticking it into a MySQL insert query, you'll also want to make sure you sanitize the inputs before submitting the query so you avoid some evil-doer from pulling some SQL injection and killing your DB.
Lastly: This is a pretty vague question so I anticipate it will be downvoted, and my response is also pretty vague. I only wrote it because it touches on an overall idea that is pretty common and is difficult to ask in a succinct way if you are just getting started with web development. You will probably get stuck quite a few times while writing this. Try narrowing down your problem to a single issue and take that issue/question to stackoverflow. You can also hit up Google, since everything you will need to do here has been written about on forums, blogs, wikis, and Q&A sites by a gajillion other folks.
I am trying to insert a value into a MySQLi row using a select box, as seen below.
<select name="post_game"><option value="minecraft">Minecraft</option></select>
But I am faced with the error:
Undefined index: post_game
Is this because I should be using a different data type as oppose to using Varchar? I am also inserting values into other MySQLi rows using < input > instead of < select >, and they seem to go through just fine, which is why I believe it may have to do with the data type, and not my code.
But here is my code anyway:
<select name="post_game"><option value="minecraft">Minecraft</option></select>
$game=$_POST['post_game'];
$query = mysqli_query($con,"INSERT INTO servers (game) VALUES ('$game')");
Varchar will work just fine. If that is your entire code that you posted it won't work since there is not post request being made, in order to do that you need a form element
<form method="post">
<select name="post_game">
<option value="minecraft">Minecraft</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
<?php
if (isset($_POST["submit"]) && isset($_POST["post_game"]))
{
$game = mysqli_real_escape_string($con,$_POST["post_game"]);
$query = mysqli_query($con,"INSERT INTO servers (game) VALUES ('$game')");
}
?>
And also think about security as well. Bind your params, I'm on my phone so I wpnt get into that. This should be enough to get you going though
I'm an absolute noob to programming and over the past 10 days or so I have been building a 'buy sell trade' website for things.
Anyway I have got to the point where I now have the ability for people to register, post ads and reply to them... but now I want to have a page where they can search through the adverts.
The search form works on 3 fields, 'make', 'model' and 'caliber' (site is for guns)
<form action="" method="get" autocomplete="off">
I'm looking for a
<input type="text" name="make" class="autosuggestmake" placeholder="Manufacturer"/>
<div class="dropdown">
<ul class="resultmake"></ul>
</div>
<input type="text" name="model" class="autosuggestmodel" placeholder="Model"/>
<div class="dropdown">
<ul class="resultmodel"></ul>
</div>
in
<select name="caliber" >
<option value="*">(Caliber) Any</option>
<option value=".177">.177</option>
<option value=".20">.20</option>
<option value=".22">.22</option>
<option value=".25">.25</option>
</select>
<input type="submit" value="Search" />
This is posted as GET data which I 'catch' with this code:
$advert = new Advert;
if (empty($_GET) === true){
$adverts = $advert->fetch_all();
} else {
$search_make = $_GET['make'];
$search_model = $_GET['model'];
$search_caliber = $_GET['caliber'];
$adverts = $advert->fetch_results($search_make, $search_model, $search_caliber);
}
My fetch_results query is this:
class Advert {
public function fetch_results($search_make, $search_model, $search_caliber) {
global $pdo;
$search_caliber = mysql_real_escape_string($search_caliber);
$search_make = mysql_real_escape_string($search_make);
$search_model = mysql_real_escape_string($search_model);
if (empty($search_make) === true){
$search_make = "*";
}
if (empty($search_model) === true){
$search_model = "*";
}
$query = $pdo -> prepare("SELECT * FROM `adverts` WHERE make = '$search_make' AND model = '$search_model' AND caliber = '$search_caliber'");
$query -> execute();
return $query -> fetchAll();
}
On my last question someone told me to start using PDO, so I did :)
My problem is when someone fills in the make field on my form and nothing else it will return nothing. I thought if the get variables were blank I would append a * and it will return anything but this is not the case :( I've been searching but I think my problem is I don't know the correct words to search to find the cure for my problem...
Any help would be greatly appreciated.
Having implemented a site with this myself, I strongly recommend Sphinx. This is what craigslist uses. It is simple enough for your needs, yet powerful enough to grow with you.
Another alternative is ElasticSearch, which I'm told is very good as well.
There are two approaches you can take. One is to rewrite the query in php based on the search conditions.
The other is a SQL solution:
SELECT *
FROM `adverts`
WHERE ('$search_make' = '' or make = '$search_make') AND
('$search_model' or model = '$search_model') AND
('$search_caliber' or caliber = '$search_caliber');
However, if the table has indexes on the columns, then this query probably will not use the indexes. Writing the php to include only the clauses with values creates a more efficient query.
Either you let your users browse "all" -- Use case = some collector looking for odd items.
Or you have a "Search By" pull down and make your users choose at least one of the search categories.
You could just send an error message if all the search criteria are blank -- but this tends to annoy users more than leading them through a set of search option screens.
I've always found myself creating two separate php files/scripts for adding a certain data and editing this data. These files weren't that much different, so I figured there should be a way how to make them into one file.
Here I'll present a very simple example to illustrate my point:
add.php:
<?php
$title = $_POST['title']; // ignore the unescaped data, this is a simple example
$text = $_POST['text'];
mysqli_query($connection,
"INSERT INTO `articles` (`title`, `text`) VALUES ('$title', '$text')");
echo'
<form>
<input type="text" name="title" value="'.$_POST['title'].'" />
<input type="text" name="text" value="'.$_POST['text'].'" />
<input type="submit" value="Add" />
</form>
';
?>
edit.php:
<?php
$id = $_GET['id'];
$title = $_POST['title']; // ignore the unescaped data, this is a simple example
$text = $_POST['text'];
// save data
mysqli_query($connection,
"UPDATE `articles` SET `title` = '$title', `text` = '$text'
WHERE `id` = $id");
// get current data
$q = mysqli_query($connection,"SELECT * FROM `articles` WHERE `id` = $id");
$d = mysqli_fetch_array($q);
$title = $d['title'];
$text = $d['text'];
echo'
<form>
<input type="text" name="title" value="'.$title.'" />
<input type="text" name="text" value="'.$text.'" />
<input type="submit" value="Add" />
</form>
';
?>
As you can see, the add and edit forms/codes are very similar, except that:
add inserts the data, while edit updates it
add inserts $_POST values into the form (if there's an error, so that the submitted data remains in the form, while edit inserts the current database values into the form (after the save is complete and the page refreshes, so that the form has the current db values)
Can these two somehow be merged into one file/code, so that if I want to add/change the form values, I don't need to edit two files separately, but will change the form only once?
You can use a INSERT ON DUPLICATE KEY UPDATE which roughly gave you :
<?php
$id = $_GET['id'];
$title = $text = '';
if ($_POST)
{
$title = $_POST['title'];
$text = $_POST['text'];
// save data
$query = "INSERT INTO `articles` (`id`, `title`, `text`)
VALUES ('$id', '$title', '$text')
ON DUPLICATE KEYS UPDATE title = title, text = text"
mysqli_query($connection, $query);
}
else if ($id)
{
// get current data
$q = mysqli_query($connection, "SELECT * FROM `articles` WHERE `id` = $id");
$d = mysqli_fetch_array($q);
$title = $d['title'];
$text = $d['text'];
}
echo '
<form>
<input type="text" name="title" value="'.$title.'" />
<input type="text" name="text" value="'.$text.'" />
<input type="submit" value="Add" />
</form>';
If it's a POST and no $id present : a new row is inserted just like an INSERT.
If it's a POST and an $id is present : if $id already exist in the table than the row is updated otherwise it's an INSERT.
If you only have an $id : show the form with existing data in it.
If it's not a POST and $id isn't populated : show an empty form.
You could use a combination of GET and POST parameters do achieve what you want. Use the GET parameters to distinguish between edit and add, i.e. /post?action=add or /post?action=edit. Based on the value of $_GET['action'] you'd know whether to render an empty form to add a post or to populate the form in with data from the DB. Then you could have a hidden field in your form, which you'd fill in with the value of $_GET['action'] and so you'd be able to know whether to INSERT or UPDATE when processing the form after submitting it.
It might be worth though to start using some framework, i.e. CakePHP, CodeIgniter, Zend Framework, etc.
I tend to make an interface for inserting and updating data which has only one method for inserting and updating. The key point for that to work is the user form that is being submitted must contain the id of the row being updated.
public method save( Object obj )
if obj.id is in database
query = "update table set attrA = obj.a, attrB = obj.b where id=obj.id"
else if obj.id < 1
query = "insert into table (a,b,c) values (obj.a,obj.b,obj.c)"
This implies that when you create a new object to be submitted, it must have id initialized to 0 or -1 (1 is the first key row for a table with int primary keys). Likewise, a form in a html file must have an <input type=hidden value=row.id name=DBID> that is populated either with a default value (null, 0, -1) or a valid id of the object being edited.
Essentially this means that the user may update arbitrary rows in the table, but granted they have authenticated themselves, this should not be a problem. Also, it is usually enough to know that the id > 0 to to an INSERT, and UPDATE otherwise. It is not necessary to verify that the id being submitted is in the database table, because when you insert you do not set the id, but rather let the DB auto-increment the primary key.
update
wow so many silly typos after only 3 beers. I hope this is readable
Here's an idea how it should look like using OOP (in my opinion).
Let's assume you have some class that represents form element called FormElement.
Then you have some generic form that should support what? Let's assume MVC:
displaying itself
adding elements
setting default values
parsing request values
getting values
validating values
So you'll build yourself an interface like
interface IForm {
public function Display();
public function AddElement( FormElement $element);
public function SetValues( array);
public function FetchPostValues();
public function GetValues();
public function Validate();
}
Then, what's common for both those forms (let's say that you want to prohibit change of email)? Everything except FetchPostValues()
So you'll build a class with one pure virtual method which will do everything that is similar:
abstract class FormArticle implements IForm {
// All methods implemented except FetchPostValues
abstract public function FetchPostValues();
}
And then just build two small classes that will define how to fetch post data:
class FormArticleEdit extends FormArticle {
public function FetchPostValues(){
if( isset( $_POST['email'])){
throw new Exception('What are you trying to achieve?');
}
// ...
}
}
And one more tip (two actually):
Implement abstract class like FormAbstract that will provide all generic methods like AddElement(), Display(). This will save you copying of those general methods every time, but will still provide you with ability to start from scratch (when using database or so directly to cache items).
Rather use framework that already has model for reusing forms (Zend is my personal favorite).