Im having trouble with this php mysql issue. I have 5 input fields with the same name, and foreach input field entered i was that to be saved in the database. But at the moment, if i input 2 fields, its inserting them plus 3 blank ones. How do i just insert the ones which are not empty
here is the html
<input type="text" name="tags[]" placeholder="Add Tags" />
<input type="text" name="tags[]" placeholder="Add Tags" />
<input type="text" name="tags[]" placeholder="Add Tags" />
<input type="text" name="tags[]" placeholder="Add Tags" />
<input type="text" name="tags[]" placeholder="Add Tags" />
here is the php
$tags = $_POST['tags'];
for($i = 0; $i < count($tags); $i++){
$tag = $_POST['tags'][$i];
$addtags = $gifs->addtags($tag, $id);
}
well, first thing is to sanitize your input, second thing is to trim each value and add this:
$tag = trim($tag);
if(!empty($tag)){
...code
Try This
$tags = $_POST['tags'];
for($i = 0; $i < count($tags); $i++){
$tag = trim($_POST['tags'][$i]);
if (!empty($tag))
$addtags = $gifs->addtags($tag, $id);
}
Remove the empty with array_filter():
$tags = array_filter($_POST['tags']);
foreach($tags as $tag) {
$addtags = $gifs->addtags($tag, $id);
}
Try this, You can use foreach
$tags = $_POST['tags'];
foreach($tags as $tag) {
$tag = trim($tag);
if (! empty($tag)) {
$addtags = $gifs->addtags($tag, $id);
}
}
Related
I have problem with the following code i am trying t write the dynamic query which will be independent to my html form. Like i don't want to write the name a every single name of field in my query i want to make it dynamic thats why using the following the approach but the problem is right after the foreach block of code just below that
any other best way kindly guide me it'll be highly appreciated.
foreach(){
}
sql.="";
problem is here this sqli like contains only the last key and values not all the keys and values
Results:
INSERT INTO Patient(patient_cell) values (033480779)';
whereas i want results like this
INSERT INTO Patient(patient_name,patient_address,patient_pass,patient_cell) values (Saba,Daska,12345,033480779)';
HTML Form
<form method="post" action="Patient_data.php">
<label>Patient name:</label>
<input type="text" name="patient_name" placeholder="Patient name">
<br>
<label>Patient Address:</label>
<input type="text" name="patient_address" placeholder="Address">
<br>
<label>Patient's Password:</label>
<input type="text" name="patient_pass" placeholder="Password">
<br>
<label>Patient Cell:</label>
<input type="text" name="patient_cell" placeholder="Enter cell no.">
<br>
<input type="submit" value="Create Record" name="Create">
</form>
code:
$record['patient_name'] = $_POST['patient_name'];
$record['patient_address']=$_POST['patient_address'];
$record['patient_pass']=$_POST['patient_pass'];
$record['patient_cell']=$_POST['patient_cell'];
$dbname= new Db();
$dbname->Add($record);
function
public function Add($record) {
$var= $record;
$sql.= "INSERT INTO Patient";
foreach ($var as $key => $value) {
$key = "{$key},";
var_dump($key);
$value = "{$value},";
var_dump($value);
}
$sql.="(".substr($key,0,-1).") values (".substr($value,0,-1).")";
function Add($record) {
$var= $record;
$sql.= "INSERT INTO Patient ([%keys%]) values ([%vals%])";
$keys = "";
$vals = "";
foreach ($var as $key => $value) {
if (!empty($keys)) {
$keys .= ",";
}
$keys .= $key;
if (!empty($vals)) {
$vals .= ",";
}
$vals .= $value;
}
$sql = str_replace("[%keys%]", $keys, $sql);
$sql = str_replace("[%vals%]", $vals, $sql);
return $sql;
}
Try this function
Note : if some field is string you should add single quote in that field.
I want to send the "fill[]" and the "item[]" and my problem is the function write cant get the values of the variables, why?
What is wrong? Im new in this stuff.
<form action="/fill_sites/fill.php" method="get">
<input type="text" size="24" maxlength="20" name="fill[0]"/>
<input type="hidden" name="item[0]value="hella_apfelschorle"/>
<input type="text" size="24" maxlength="20" name="fill[1]"/>
<input type="hidden" name="item[1]" value="volvic_wasser"/>
..... so on
<input type="submit" value="Abschicken"/>
------------------------------------------------------------>[fill/php]>
$fill[0] = $_GET["fill[0]"];
$fill[1] = $_GET["fill[1]"];
$fill[2] = $_GET["fill[2]"];
$fill[3] = $_GET["fill[3]"];
$fill[4] = $_GET["fill[4]"];
$fill[5] = $_GET["fill[5]"];
$fill[6] = $_GET["fill[6]"];
$fill[7] = $_GET["fill[7]"];
$fill[8] = $_GET["fill[8]"];
$fill[9] = $_GET["fill[9]"];
$item[0] = $_GET["item[0]"];
$item[1] = $_GET["item[1]"];
$item[2] = $_GET["item[2]"];
$item[3] = $_GET["item[3]"];
$item[4] = $_GET["item[4]"];
$item[5] = $_GET["item[5]"];
$item[6] = $_GET["item[6]"];
$item[7] = $_GET["item[7]"];
$item[8] = $_GET["item[8]"];
$item[9] = $_GET["item[9]"];
write($counterFilename[$item[]], $fill);
you can do this by following code. it will get complete array.
$item = $_Get['item'];
$fill= $_Get['fill'];
use php's foreach statement to retrieve the content of fill and item
$fills = $_GET['fill'];
foreach($fills as $fill)
{
//do something with $fill
}
and the same for $item
I'm working on a page with many insert fields.
how can i shorten the following code?
$title_1 = $_POST['title_1'];
$content_1 = $_POST['content_1'];
$link_1 = $_POST['link_1'];
$img_link_1 = $_POST['img_link_1'];
$title_2 = $_POST['title_2'];
$content_2 = $_POST['content_2'];
$link_2 = $_POST['link_2'];
$img_link_2 = $_POST['img_link_2'];
$title_3 = $_POST['title_3'];
$content_3 = $_POST['content_3'];
$link_3 = $_POST['link_3'];
$img_link_3 = $_POST['img_link_3'];
You could loop through the $_POST array like this:
foreach ($_POST as $key => $value) {
${$key} = $value;
}
This will make your post variable like $_POST['title_1'] into $title_1
Remember your post names will have to be the exact names you want your variables to be referenced by.
I would do:
$howmany = 3; // How many sets of fields are submitted.
for($i=0;$i<$howmany;$i++){
$field[$i]['title'] = $_POST['title_'.$i];
$field[$i]['content'] = $_POST['content_'.$i];
$field[$i]['link'] = $_POST['link_'.$i];
$field[$i]['img_link'] = $_POST['img_link_'.$i];
}
Then you can access data in $field[1]['title'] form.
You can use extract (http://php.net/manual/en/function.extract.php): extract($_POST)
But you should be careful -- what if the client POSTs user_id, or something? At the least, you should specify that $_POST values won't overwrite already-defined variables: extract($_POST, EXTR_SKIP)
I redid this answer after you edited your post. Use variable variables.
foreach ($_POST as $key => $val)
{
if (preg_match('/^(([a-z]+_)+\d)$/', $key, $match)
{
$$match[0] = $val;
}
}
Use [a-z0-9] or [a-zA-Z0-9] as alternatives.
<?php
$key_prefixes = array (
'title',
'content',
'link',
'img_link'
);
$i = 1;
while (true) {
$post_values_missing = 0;
foreach ($key_prefixes as $key_prefix) {
$key = $key_prefix . '_' . $i;
if (!isset($_POST[$key])) {
$post_values_missing += 1;
continue;
};
$val = $_POST[$key];
// do something with $val
}
// did you get any values through this iteration?
$post_values_exist_bool = (count($key_prefixes) !== $post_values_missing);
// if not, you must've gotten them all
if (false === $post_values_exist_bool) {
break;
}
$i += 1;
}
The cleanest way to do this would be to use PHP's POST data processing capabilities to do the work for you.
Consider using your HTML form names as follows:
<form action="{url}" method="post">
<input type="text" name="data[0][title]" />
<input type="text" name="data[0][content]" />
<input type="text" name="data[0][link]" />
<input type="text" name="data[0][image_link]" />
<input type="text" name="data[1][title]" />
<input type="text" name="data[1][content]" />
<input type="text" name="data[1][link]" />
<input type="text" name="data[1][image_link]" />
...
</form>
In PHP extract the data as follows:
$data = $_POST['data'];
This shortens your PHP code to just one line. This statement will directly give you an array in PHP of the data form input. A var_dump will look as follows:
array (
0 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
1 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
...
)
You don't have to change your name, just make it array;
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
PHP:
extract($_POST);
$count=count($title);
for($i=0;$i<$count;$i++) {
//You can perform your any function on this loop, to get title use $title[$i]
}
<form action="form.php" id="form">
<input type="text" name="name_1"><input type="text" name="city_1"><input type="text" name="country_1">
<input type="text" name="name_2"><input type="text" name="city_2"><input type="text" name="country_2">
<input type="text" name="name_3"><input type="text" name="city_3"><input type="text" name="country_3">
<input type="submit">
</form>
How is the best method for get this data in form.php file? This is generated with jQuery. Can be 3 (as now) or 30.
In form.php i have:
$data = new Data();
$data->name = $_POST['name_1'];
$data->city = $_POST['city_1'];
$data->country = $_POST['country_1'];
$data->save();
$data = new Data();
$data->name = $_POST['name_2'];
$data->city = $_POST['city_2'];
$data->country = $_POST['country_2'];
$data->save();
$data = new Data();
$data->name = $_POST['name_3'];
$data->city = $_POST['city_3'];
$data->country = $_POST['country_3'];
$data->save();
But if there is over 3? I would like use foreach, but how? How can i generated input or get this data?
Use name[], city[] and country[] as your input names. Then they'll come through to PHP as arrays which you can iterate with foreach.
If you can change the names of the input elements you could do it like that:
<input type="text" name="items[1][name]"><input type="text" name="items[1][city]"><input type="text" name="items[1][country]">
<input type="text" name="items[2][name]"><input type="text" name="items[2][city]"><input type="text" name="items[2][country]">
<input type="text" name="items[3][name]"><input type="text" name="items[3][city]"><input type="text" name="items[3][country]">
The numbers don't have to be adjacent but the have to be unique. To convert the $_POST-data to your data-model would then look like that:
$items = $_POST['items'];
$dataList = array();
foreach($items as $item) {
$data = new Data();
$data->name = $item['name'];
$data->city = $item['city'];
$data->country = $item['country'];
$dataList[] = $data;
}
Of course you can add as many items as you want.
If you can't change the names of the input elements then you could use one of the other solutions. I would only modify them so that the number of elements is not hard coded like:
$dataList = array()
for($i = 1; isset($_POST["name_$i"]); ++$i) {
$data = new Data();
$data->name = $_POST["name_$i"];
// ... and so on
$dataList[] = $data;
}
Of course, with that solution the numbers must be continuous/adjacent.
You can use your for each with on time built strings like 'name_.$i', with $i as a counter
You can use a for loop:
for ($i = 1; $i <= 3; $i++) {
$data = new Data();
$data->name = $_POST['name_'.$i];
$data->city = $_POST['city_'.$i];
$data->country = $_POST['country_'.$i];
$data->save();
}
But if you could change your html like:
<input type="text" name="name[]"><input type="text" name="city[]"><input type="text" name="country[]">
<input type="text" name="name[]"><input type="text" name="city[]"><input type="text" name="country[]">
<input type="text" name="name[]"><input type="text" name="city[]"><input type="text" name="country[]">
You will not need to know the count.(name_1,name_2 would be better to be the id but not name)
foreach ($_POST['name'] as $index => $name) {
$data = new Data();
$data->name = $name;
$data->city = $_POST['city'][$index];
$data->country = $_POST['country'][$index];
$data->save();
}
I am fairly new to PHP so please bear with me :)
What I am trying to do if place URL's into a text area, then pull in the meta data for each.
I have made the script, but when I place more then one URL into the text area it only returns data for the last URL entered, I thought maybe you guys can help me :)
<form method="POST">
<textarea name="TAData">
</textarea>
<input type="submit" value="submit"/>
</form>
<div id="checkboxes">
<input type="checkbox" name="vehicle" value="PR" /> Show me the PR<br />
<input type="checkbox" name="vehicle" value="KW Tag" /> Show me the KW tag<br />
<input type="checkbox" name="vehicle" value="Title Tag" /> Show me the Title tag<br />
</div>
<div id="checkboxes">
<input type="checkbox" name="vehicle" value="1stH1" /> Show me the 1st H1<br />
<input type="checkbox" name="vehicle" value="2ndH1" /> Show me the 2nd H1 tag<br />
<input type="checkbox" name="vehicle" value="SeedKW" /> Show me Seed KW's<br />
</div>
<div id="nofloat"></div>
<?php
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
foreach ($TAarray as $key => &$line) { $line = trim($line); }
// get the meta data for each url
$tags = get_meta_tags($line);
unset($tags["content-type"]);
unset($tags["page-type"]);
unset($tags["page-topic"]);
unset($tags["audience"]);
unset($tags["content-language"]);
echo '<tr>';
foreach ($tags as $meta)
{
echo '<td>' . $meta . '</td>';
}
echo '</tr>';
?>
The closing } after where you use trim on the line means that the foreach ends and only the last line is available after the loop for the other operations. Just move that bracket to the end.
If you use foreach with references, it's good practice to remove that reference after the loop:
foreach ($TAarray as $key => &$line)
{
$line = trim($line);
}
unset($line); # remove the reference for safety reasons
But as you don't iterate over $TAarray after that code, the code is superfluous anyway. Don't write superfluous code. I suggest the following:
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
$TAarray = array_map('trim', $TAarray);
And I suggest you put that into a function of it's own:
/**
* #param string $html
* #return string[] lines
*/
function getTrimmedTextLinesArrayFromHTMLBlock($html)
{
$text = strip_tags($html);
$lines = explode("\n", $text);
$trimmed = array_map('trim', $lines);
return $trimmed;
}
You can then use it wherever you see fit. You can also test this function independently with different input:
$lines = getTrimmedTextLinesArrayFromHTMLBlock($_POST['TAData']));
$blacklist= array("content-type", "page-type", "page-topic",
"audience", "content-language");
foreach ($lines as $line)
{
if (! $tags = get_meta_tags($line)) continue;
echo '<tr>';
foreach ($tags as $key => $meta)
{
if (in_array($key, $blacklist)) continue;
echo '<td>' . $meta . '</td>';
}
echo '</tr>';
}
I hope this is helpful.