Create comma separated list of links with variable in PHP - php

I have a variable which renders a list of usernames. Now, I need to add a link to each username. The link is built from a fixed URL and the username as a variable.
Example link:
https://www.example.org/something?userid=$username
$usernames = $_POST['username'];
$username = '';
foreach($usernames as $value) {
$username .= "'" . $value . "', ";
}
$username = rtrim($username, ', ');
And then, I have the construction of the list:
<?php $urls = explode(',', $usernameid);
$nritems = count ($urls);
$positem = 0;
foreach($urls as $key => $usernameid)
{
echo "<a href="https://www.example.org/something?userid=' . $usernameid .
'">'. $usernameid . '</a>";
if (++$positem != $nritems) { echo ", ";}
}?>
The variable is also used in other parts of the code, so I can't change it. The list is not displaying now.
Any help is appreciated.
Update: the form:
<form action="list.php" method="post" autocomplete="off">
<div id="usrselect">
<label>Select user <input type="text" name="username[]" id="userid" class="typeahead" required/></label>
</div>
<div class="button-section"> <input type="submit" name="List" /></div>
</form>

If you just want to get your quotes right:
echo ''.$usernameid.'';
or
echo "{$usernameid}";
or
echo sprintf('%d', $usernameid, $usernameid);

The working solution, for those who might face the same problem:
<?php $urls = explode(',', $usernameid);
$nritems = count ($urls);
$positem = 0;
$displayuser = array("'", " ");
foreach($urls as $key => $usernameid)
{
echo ''.str_replace($displayuser, "", $usernameid).'';
if (++$positem != $nritems) { echo ", ";}
}?>

Related

Form is submitting only the final row data in a foreach loop, not the correct selection information

I had originally had the form inside of the foreach(ran into issues that seemed unsolvable because it would call the function as many times as the foreach had listed).
So now, with the <form> outside of the foreach it will only submit the data from the final collection in the foreach loop. But what I need it to do is send the data depending on which item in the foreach loop is checked.
This is my function for submitting the information to the database:
function user_add_new() {
global $wpdb;
$bookTOadd = $_POST["book"];
$listTOadd = $_POST["listID"];
$userID = $_POST["user"];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
And this is my foreach loop with the form outside of it:
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
?>
<?php if($r == ''.$current_user->ID.''|| $r == 'administrator') { ?>
<div class="user-wrap">
<div class="inner-wrap">
<!---entire checkbox--->
<div><span class="check">
<input type="checkbox" value="" onChange="this.form.submit()">
<input type="hidden" name="item" value="<?php echo $t;?>">
<input type="hidden" name="listID" value="<?php echo $o;?>">
<input type="hidden" name="userID" value="<?php echo $current_id;?>">
</span></div>
<!---entire checkbox--->
<!---info from book--->
<div>
<b><?php echo $s; ?></b><br>
<?php echo $d; ?>
</div>
<!---info from book--->
</div>
</div>
<?php } else {
}; ?>
<?php
};
?>
</form>
I did check the output with var_export($_POST); and it indeed does only return the data for the final item in the foreach loop when it needs to return data depending on which foreach item is checked
I have been stuck on this single form for hours now, I think I need a fresh mind to help find the solution. I truly appreciate any help!
Try this as your form:
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
I've removed the many <?php ?> statements and echoed the HTML in PHP. Also notice checkbox input has name='checkbox[]' value = '$index'.
The [] after the name means the values of the checked checkboxes will come through as an array in $_POST["checkbox"]. Since you are immediately submitting the form as soon as one is checked, you should only have one value in this array so we access that in the user_add_new() function with $_POST["checkbox"][0]
Then this is the function:
function user_add_new() {
global $wpdb;
$value = $_POST["checkbox"][0];
$bookTOadd = $_POST["item" . $value];
$listTOadd = $_POST["listID" . $value];
$userID = $_POST["userID" . $value];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
You had $bookTOadd = $_POST["book"]; but I couldn't see an input with book as a name so I assume this should be item?

Insert batch to MySQL with PHP/PDO

I have an form for bulk add domains and these domains could have one or more countries and one language attribute.
My form (reduced to code):
Add domains:
<textarea name="bulk" rows="10" class="form-control no-resize"><?php echo $_POST['bulk']; ?></textarea>
Choose one or more countries:
<div class="checkbox">
<?php
if ($queries->query("SELECT * FROM countrycodes ORDER BY code ASC")) {
if ($queries->count() > 0) {
$contents = $queries->fetchAll();
foreach ($contents as $content) {
?>
<input type="checkbox" id="country_<?php echo $content->code; ?>" name="country[]" value="<?php echo $content->code; ?>" <?php if (in_array($content->code, $_POST['country'])) echo "checked = 'checked'"; ?> />
<label for="country_<?php echo $content->code; ?>"><?php echo $content->country; ?></label><br />
<?php }}} ?>
</div>
Choose the language:
<div class="radio">
<?php
if ($queries->query("SELECT * FROM langcodes ORDER BY code ASC")) {
if ($queries->count() > 0) {
$contents = $queries->fetchAll();
foreach ($contents as $content) {
?>
<input type="radio" name="lang" id="lang_<?php echo $content->code; ?>" value="<?php echo $content->code; ?>" <?php if ($content->code == $_POST['lang']) { ?>checked="" <?php } ?> />
<label for="lang_<?php echo $content->code; ?>"><?php echo $content->language; ?></label><br />
<?php }}} ?>
</div>
Get data from submit:
if (isset($_POST['addData'])) {
$doms = explode("\n", str_replace("\r", "", $_POST['bulk']));
$coun = implode(", ", $_POST['country']);
$lang = $_POST['lang'];
}
I found this one for bulk inserts:
$d = ['Osian', 'Williams', 1];
$data = array_fill(0, 1000, $d);
$db = new PDO('mysql:host=localhost;dbname=MYDB','MYUSER','MYPASS');
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO members (firstname, surname, title) VALUES (?,?,?)');
for($i=0;$i<count($data);$i++) {
$stmt->execute($data[$i]);
}
$db->commit();
I have no idea, how to get my data (domains, countries, lang) working for this code.
And, I need to check if a domain is already in the db, but only, if the domain has the same language.
So, would be nice to get some help.
I found an solution. Was a bit confused at the beginning, how to add country and lang to the list of domains. But the country data and lang data are static - so I just need to loop through the domains.
That's my solution and it works:
if (isset($_POST['addData'])) {
$doms = explode("\n", str_replace("\r", "", $_POST['bulk']));
$coun = implode(", ", $_POST['country']);
$lang = $_POST['lang'];
$queries->transStart();
foreach ($doms as $dom) {
if ($queries->query("SELECT domain FROM websites WHERE domain = ? AND lang = ?", [$dom, $lang])) {
if ($queries->count() > 0) {
$infoBox = "error_duplicate";
} else {
$queries->query("INSERT INTO websites (domain, country, lang) VALUES (?,?,?)", [$dom, $coun, $lang]);
$infoBox = "success";
}
}
}
$queries->transStop();
}

How to select certain term depending on search?

So I am wanting the user to be able to search by either keyword or ID number. If they search "test" right now for example it will pull all the entries with test which is what I want it to do for the keyword part of the search. However, I also want the user to be able to search my specific a specific ID# and just pulling that specific entry. I am unsure how I would go about doing this. I tried doing some sort of OR statement but it did not pull any entries.
Search box form
<div class ="search" id="browse">
<p> Find your appointment below or search by keyword</p>
<form id="" class="searchbar" action="searchAppt.php" method="get">
<input type="text" name="terms" size="40" class = "sbar" placeholder="Search by issue keyword or ID" oninput="validity.valid||(value='');"
onblur="if (this.value == '') {
this.value = 'Enter keyword or ID';
}"
onfocus="if (this.value == 'Enter keyword or ID') {
this.value = '';
}"/>
<button type="submit" class = "btn">Search</button>
</form>
</div>
searchAppt.php
if (filter_has_var(INPUT_GET, "terms")) {
$terms_str = filter_input(INPUT_GET, 'terms', FILTER_SANITIZE_STRING);
} else {
echo "There were no appointments found.";
include ('includes/footer.php');
exit;
}
//explode the search terms into an array
$terms = explode(" ", $terms_str);
$sql = "SELECT * FROM appointments WHERE 1";
foreach ($terms as $term) {
$sql .= " AND email = '". $_SESSION['email'] ."' AND issue LIKE '%$term%' OR id ='%term%'
";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<br /><br /><center><h1>My Ticket(s)</h1><br />
<div class='table'>
<div class='tr'>
<div class='td'><b>Ticket #</b></div>
<div class='td'><b>Issue</b></div>
<div class='td'><b>Date</b></div>
<div class='td'><b>Ticket Details</b></div>
</div>";
// output data of each row
while($row = $result->fetch_assoc()) {
$starttimepast = strtotime($row["start_time"]); //converts date time received from MySQL into a string
$datepast = date("m/d/y", $starttimepast);
echo "<div class='tr'>
<div class='td'>".$row["id"]."</div>
<div class='td'>".$row["issue"]."</div>
<div class='td'>".$datepast."</div>
<div class='td'><form action='ticketdetails.php' method='post'>
<input type='hidden' name='id' value='".$row["id"]."'>
<input type='submit' value='Ticket Details'></form>
</div>
</div>";
}
echo "</div>";
echo "<br /><center><a href='myProfile.php'><h4>Go back to my profile</h4></a></center>";
include ('includes/footer.php');
} else {
echo "<br /> <br /><center><h3>Your search <i>'$terms_str'</i> did not match any appointments</h3></center>";
echo "<center><a href='myProfile.php'><h4>Go back to my profile</h4></a></center>";
echo "<br />";
exit;
}
?>
<?php
// clean up resultsets when we're done with them!
$query->close();
// close the connection.
$conn->close();
Perhaps it will help to explicitly group the terms:
$sql = "SELECT * FROM appointments WHERE email = '" . S_SESSION['email'] . "'";
$exprs = array();
foreach ($terms as $term) {
$exprs[] = "(issue LIKE '%$term%' OR id LIKE '%$term%')";
}
if (!empty($exprs)) {
$sql .= ' AND (' . join(' OR ', $exprs) . ')';
}
The result in this case will include records that matched any of the terms.
Note: It would be good to use a DB API like laravel/PDO/mysqli to simplify the query building and properly escape the values.

php sorter script only outputting the same data even though i am asking it to do diffrent

okay so i have made the following script to sort some data i have in this format
0|1|2
heres my script (this now works)
<html>
<body>
<form method="post">
<div align="center"><textarea name="mp" cols="60" rows="10">0|1|2</textarea><br />
Delim: <input type="text" name="delim" value="|" size="1" /> data1: <input type="text" name="mail" value="0" size="1" /> data2: <input type="text" name="pwd" value="1" size="1" />
<input type="submit" value=" send " name="btn-submit" />
</div>
</form>
</body>
</html>
<?php
if (isset($_POST['mp'], $_POST['delim'], $_POST['btn-submit'], $_POST['mail'], $_POST['pwd'])) {
$mps = preg_split('/\r\n|\r|\n/', $_POST['mp']);
// Create an array to store results
$result_data = array();
// Iterate over requests
foreach ($mps as $mp) {
$mp = explode($_POST['delim'], $mp);
// Store the account details in variables
$email = $mp[$_POST["mail"]];
$password = $mp[$_POST["pwd"]];
// Prepare a reusable string
$result_string = "" . $email . " : " . $password . "";
// Add result to the array
$result_data[] = $result_string;
}
// Store of results complete. We now display them.
if (count($result_data)) {
echo "<ul
list-style-type: none;
>";
foreach ($result_data as $result_data_entry) {
echo "<li list-style: none;>" . $result_data_entry . "</li>";
}
echo "</ul>";
}
}
?>
i would now like to save the results into a text file also
any help would be brilliant .
i am writing this extra line as my post has way way too much code .
You aren't using the data1 and data2 fields anywhere in your PHP.
I think instead of this:
list($email, $password) = $mp;
you need
$email = $mp[$_POST["mail"]];
$password = $mp[$_POST["pwd"]];
It's also worth noting that the values supplied in those two fields will be zero based.

Compute 1st value on multiple values on a checkbox

I was trying to make a COMPUTERIZED ORDERING SYSTEM. My problem is how can I compute the 1st value on my checkbox. The second value on the checkbox will be posted on the summary of orders.
Once I've check all those three, it will compute the total amount of the menu and to display the selected menu on the summary of orders. But I can't figure out how can I display the total amount.
Can anybody guide me how to compute the total on my 1st value on the checkbox?
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" name="go" value= "Total">
</form>
<?php
//tosilog
$ts = $_POST['ts'];
$value = explode("|",$ts[0]);
echo $value[0];
echo $value[1];
//chiksilog
$cs = $_POST['cs'];
$value = explode("|",$cs[0]);
echo $value[0];
echo $value[1];
//porksilog
$ps = $_POST['ps'];
$value = explode("|",$ps[0]);
echo $value[0];
echo $value[1];
?>
<!-- compute for the 1st value on checkbox -->
<?php
$ts=$_POST['ts[0]'];
$cs=$_POST['cs[0]'];
$ps=$_POST['ps[0]'];
?>
<?php $compute = $ts[0] + $cs[0] + $ps[0];?>
<?php echo "$compute " ; ?>
If you're getting an array of checkbox elements, and they are numeric, you can use array_sum(). Not sure I understand your suggested structure, but I'll give you a code sample here based on the existing form structure. Then I'll post another bit to try to make this simpler for you. Executive summary: You do not need all the variables that are created by this form structure.
<?php // RAY_temp_user193.php
error_reporting(E_ALL);
$total = 0;
$inputs = array();
$errors = array();
if (!empty($_POST))
{
if (!empty($_POST['ts']))
{
foreach ($_POST['ts'] as $ts)
{
$inputs[] = current(explode(' |', $ts));
}
}
else
{
$errors[] = 'Tosilog';
}
if (!empty($_POST['cs']))
{
foreach ($_POST['cs'] as $cs)
{
$inputs[] = current(explode(' |', $cs));
}
}
else
{
$errors[] = 'Chiksilog';
}
if (!empty($_POST['ps']))
{
foreach ($_POST['ps'] as $ps)
{
$inputs[] = current(explode(' |', $ps));
}
}
else
{
$errors[] = 'Porksilog';
}
// IF ERRORS
if (!empty($errors))
{
echo 'UNABLE TO PRINT COMPLETE TOTAL. MISSING: ' . implode(',', $errors);
}
$total = array_sum($inputs);
if ($total) echo "<br/>TOTAL: $total <br/>" . PHP_EOL;
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$form = <<<ENDFORM
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;
See http://www.laprbass.com/RAY_temp_miggy.php
This is probably more along the lines of the way I would do it. The script knows what goes into the HTML and it knows exactly what to expect in the POST request. It is easy to add or remove different inputs. Often these kinds of inputs come from a data base table.
<?php // RAY_temp_miggy.php
error_reporting(E_ALL);
$total = 0;
// EXPECTED INPUTS
$inputs = array
( 'Tosilog' => 40
, 'Chiksilog' => 40
, 'Porksilog' => 45
)
;
if (!empty($_POST))
{
// ACTIVATE THIS TO SEE WHAT WAS SUBMITTED
// var_dump($_POST);
// SUM OF THE ELEMENTS
$total = array_sum($_POST);
echo "TOTAL: $total";
// SUM OF THE EXPECTED INPUTS
$expect = array_sum($inputs);
if ($total != $expect) echo " BUT THERE MAY BE INCOMPLETE INPUTS!";
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$checkboxes = NULL;
foreach ($inputs as $name => $value)
{
$checkboxes
.= '<input name="'
. $name
. '" type="checkbox" value="'
. $value
. '" />'
. $name
. '<br/>'
. PHP_EOL
;
}
$form = <<<ENDFORM
<form method="post">
$checkboxes
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;

Categories