Multiple PHP MySQL Insertions - php

I can't think of an easy way to explain what I'm trying to accomplish..
Inserting data into MySQL using php is simple, yet I need to be able to give users the option to add more text inputs in one form...
Just for example purpose...
Users can create a shopping list, the page loads with 15 inputs for 15 items they wish to insert into their shopping list...
At the bottom, they can have the option to add another item, and when clicked, it will show an additional text input..
I've looked for examples but off the top of my head I can't think of any...
if(isset($_POST['createList']){
$item=addslashes(strip_tags($_POST['item']));
}
mysqli_query("INSERT INTO shoppingLists (id,itemName) VALUES (``,`$item`)");
How do insert multiple items with a simple POST?
I was hoping it's possible to use JQuery to add additional input fields.. but how is something like this accomplished on the PHP side?
I do hope I've explained this well enough haha.

You can use an array for your input name attribute
<input type="text" name="item[]" />
And you can browse it by looping through your variable $_POST['item'], that now contains an array with an entry for each field in your form.

I use jQuery .clone() for this.
html:
<div id=="ShoppingList">
<input class="item" name="item[]" />
<input type="button" onclick="addAnotherItem()" />
</div>
js:
function addAnotherItem(){
$("#ShoppingList input.item:first").clone().val("").appendTo("#ShoppingList");
}
I use .val("") so that whatever value the first input has isn't copied to the new one.

Sample Code For This inserting multiple images
if(isset($_POST['addSpace'])){
$spaceTitle = mysql_real_escape_string($_POST['title']);
$spaceBody = mysql_real_escape_string($_POST['text']);
if($_FILES['SliderImage']['tmp_name'] != "" ){
if (($_FILES["SliderImage"]["type"] == "image/jpeg")
&& ($_FILES["SliderImage"]["size"] < 2000000))
{
if ($_FILES["SliderImage"]["error"] > 0)
{
echo "<div class='error_box'><p>Error :: " . $_FILES["SliderImage"]["error"] . ".</p></div>'";
}else{
$path = "../images/prisma-img/demo/services/";
$path2 = "images/prisma-img/demo/services/";
$num = mt_rand();
if (file_exists($path . $num.".jpg" ))
{
echo "<div class='error_box'>"."(".$num .")".
" already exists. "."</div>";
}else{
if(move_uploaded_file($_FILES["SliderImage"]["tmp_name"],$path . $num.".jpg" )){
$mysqlPath = $path2. $num.".jpg" ;
$result = $db->insert("pages","pageTitle, pageImage, pageBody, pageSlug ", "'$spaceTitle','$mysqlPath','$spaceBody','services'");
if($db->affected_rows()){
$id=mysql_insert_id();
echo '<div class="valid_box"><p>Success :: Services successfully Added.</p></div>';
echo "<meta http-equiv='refresh' content='1; url= add-services-slide.php?id=".$id."' />";
}
}
}
}
}else{
echo '<div class="error_box"><p>Error :: Only JPEG file allowed.</p></div>';
}
}
}
?>
Hope that this will help u.

Related

Input Box is not appearing?

I coded adding comments function to RSS articles
In the twists and turns, it is in php coding to show and enter comments. However, the input box does not appear.
Here is the php code:
$url = "./comments/" . $q.".txt";
//댓글 파일에서 컨텐츠 문자열 가져오기
$txtcomment = file_get_contents($url,true);
//댓글 나열
echo "<ol>";
if ($q !== "" ) {
$comm = $txtcomment;
$arr = [];
$arr = explode("--",$comm);
for ($i=4;$i<count($arr);$i++) {
echo "<li>".$arr[$i]."</li>";
}
} else {
echo "해당기사가 없습니다.";
}
echo "</ol>";
//중첩검색&결과내 검색 폼 만들기
echo "<br><form class=\"category B\" >
Comment: <input type=\"text\" name=\"comment1\" id=\"comment1\" onkeyup=\"inputComment()\" >
</form>";
Why?
Thank for your concern.
Since I use RSS, I presume that php does not properly pass the attributes of the input tag in between. I started to change the old coding.
In other words, I decided that the Show Comments and the input comments were different from the beginning.
getrss.php code as below at first.
echo " <option id=".$i." onclick=\"showComment".$i."(this.value)\" value=".$item_link4."> Show Comments </option>";
but, I added the input code as like
echo " <option id=".$i." onclick=\"showComment".$i."(this.value)\" value=".$item_link4."> Show Comments </option>";
echo "댓글: <input type='text' name='inputComment' size='200' id='input".$i."' onclick='inputComment".$i."(this.value)' >
<input type='text' name='txtfile' id='txt".$i."' value=".$item_link4." hidden>
<div id='comment".$i."'><b>information will be listed here.</b></div>";
And, I make input box as a below picture.
In the end, I am trying to solve the problem in a roundabout way.
But, I still wonder why ajax's ajax is not working!!
After I input my comment, at once I see that.
further coding makes a below picture.
Thanks a lot for your sharing.

Get the dynamically generated name from the form into the $_POST

I'm currently working on a personal content management system project, but I've run into a problem.
<ul>
<?php
if(!$result) { //Check for result
die("You have no pages &#9785 Why not create one?");
} else {
while ($pages = mysqli_fetch_assoc($result)) { //Loop through results
?>
<li class="triple"><span><?php echo $pages["title"]?></span><span><?php echo $pages["visible"] ?><span /><form action = "editPage.php" method="post"><input type="submit" value="Edit Page" name="<?php $pages["title"];?>" /></form></li> //Create li elements for each result that gets created
<?php
};
};
?>
</ul>
Basically I'm using a query to results from a MySQL table and make a list of pages, the problem I've run into is that on the end form what I want to happen is I want a session variable to be stored saying which page is going to be edited, but I can't use $_POST in the form at the end to get the name because obviously the name is automatically generated from the table. Each person who uses it would have a different name for a page so I can't just get one name e.g. $_POST['homepage'].
If anyone can offer any advice on how to solve my problem or even how to come up with a better solution to store which page will be edited as it goes onto another page (editPage.php) that would be great.
Use $_SESSION[] to store the data for your $page arrays and access it again on editPage.php. You will need to make sure you call start_session(); on both pages though for it to work as expected. Since you're creating multiple forms and don't know which one will be submitted at the time PHP is running you would need to store all the pages in your $_SESSION and then iterate through them to check for the one which was selected in editPage.php:
$_SESSION['pages'] = array();
while ($page = mysqli_fetch_assoc($result)) {
$_SESSION['pages'][] = $page;
echo "<li class=\"triple\">
<span>".$page["title"]."</span>
<span>".$page["visible"]."</span>
<form action=\"editPage.php\" method=\"post\">
<input type=\"hidden\" name=\"pageID\" value=\"".$page['id']."\">
<input type=\"submit\" value=\"Edit Page\">
</form>
</li>";
}
Then in editPage.php
foreach($_SESSION['pages'] as $page){
if($page['id'] == $_POST['pageID']){ $editpage = $page; break; }
}
// do stuff with $editpage data
Another option would be to use serialize($page) and send the array with the form data in a hidden input element.
<input type='hidden' name='data' value='<?php echo serialize($page); ?>'>
Then you can use $editpage = unserialize($_POST['data']); to turn it back into an array in editPage.php.

Approved method to navigate between pages on same website

I have researched many places to find an answer to this question, but they never quite answer my real question: What is the best/approved way to move to a new page within the same website? I have read that it is bad to use window.location because search engines will think you are hiding something. But, when I don't want to open a new window (window.open), then I don't know how else to do it. I use href anchors in links and form actions, where appropriate. But when I have menus or buttons with onclick, then I need something else.
Here's an snippet of my code:
my javascript: (with one option commented)
function gotoCat() {
var catcdF = document.catSelect.catcd.value;
<?php
echo "window.location.href='http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF; ";
/*
echo "window.open('http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF,'','resizable=1,scrollbars=1,toolbar=1,top=50,left=300,width=950,height=800,location=0'); ";
*/
?>
}
My dynamic SELECT list in a form (within PHP):
echo " <select name='catcd' id='catcd' size='8' onclick=gotoCat() > \n";
// display list of categories
if ($numcats == 0) { // print message text only
echo "<option value='0' >".$catMsg."</option> \n";
}
else {
for ($i=1; $i<=$numcats; $i++) {
$catcd_db = $catAry[$i][1];
$catName_db = $catAry[$i][2];
echo "<option value='".$catcd_db."'> ".$catName_db." </option> \n";
}
}
echo "</select>";
So, as you can see, I just want a method to allow the user a choice and then automatically go to the correct web page once selected. This is not always in a select list. Often it's when they want to exit or get an error:
if (mysqli_connect_errno()) {
echo "<br/> <p style='text-align:center;'> <button type='button'
class='buttonStyle' style='padding: 4px 20px;' value='Exit' ";
echo "onClick=\"window.location.href='http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev'\" > ";
echo "Exit </button></p> ";
}
I cannot use "go back" because they need to go to a prior page, not the form they came from.
So, unless my navigation methods are really off-the-mark, I guess I need to know the acceptable method for using javascript onClick to move to the next page in the same website. Is window.location okay, or should I use something else?
Any opinions or suggestions are welcome!
To navigate to another page using Javascript, use:
window.location.href = "url";
That's how it's done and there's nothing wrong about it.
For the sake of argument, you could create a hidden link and simulate a click on it, but as I said, there's really no need.
You can use php header('location') instead:
<form action="submit.php">
<input type="hidden" value="test" name="hidden1" />
<input type="submit" Value="Exit" ... />
submit.php
<?php
if (isset($_POST['hidden1'])
{
header('Location: http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev');
exit;
}
?>
More info about header('Location ...');:
http://php.net/manual/en/function.header.php
Instead of a hidden, you use your select's value and get it via the $_POST variable.

give a user X number of chances to input a value in PHP

Hi I am a newbie learning PHP ( & on stackoverflow too)- I am trying to solve a simple problem but unable to do. I hae already searched on google and stackoverflow before posting a question as I didnt want to waste other time but for a week now am unable to solve this issue.
I am writing a simple program in php that lets user input a number and checks if the value entered is 5. If true it echo's "you win" else "try again". I am able to do this
The tricky part for me is I want to give him only 10 chances and try as I might using basic PHP am unable to do this. Have tried using if, for, do while but am unable to "loop the html"..I dont know jquery etc and am trying to accomplish this with PHP only. I havent yet progessed to learning sessions etc. Thanks in advance
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="hidden" name="cnt" value=<?php $cnt=0 ?>>
<input type="submit" name="go">
</body>
</html>
<?php
$i=0;
if ($_POST['num']!=5)
{
$i++;
echo $i;
echo " Please try again";
}
else
echo "You win the game";
?>'
You need to store the variable in some manner such that it persists. in your script, you are setting $i to 0 each time it runs. Plus you are setting the value incorrectly in your hidden input.
One way of doing this is using a Session variable, such as $_SESSION['cnt']
My PHP is a bit rusty, but here's an example using Session variables:
$max_guesses = 10;
if( !isset($_SESSION['cnt']) ){
$_SESSION['cnt'] = 0;
}
if( $_SESSION['cnt']++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
If you don't want to, or can't use a session variable, you could use the hidden input field, like you tried to:
<?php
if( !isset($_POST['cnt']) ){
$cnt = 0;
} else {
$cnt = $_POST['cnt'];
}
if( $cnt++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
?>
<input type='hidden' name='cnt' value='<?php echo $cnt ?>' />
(Note if your form uses GET instead, just replace $_POST with $_GET or you can use $_REQUEST if you're not sure, but probably better not to.
After successful login of the user set the chances variable to 10 like this.
$_SESSION['nofchances']=10;
After setting this flag on the successful authentication page. Redirect to your PLAIN html code.
EDITED :
question.html
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="submit" name="go">
</body>
</html>
gullible.php
<?php
if($_SESSION['nofchances']!=0)
{
if ($_POST['num']!=5)
{
$_SESSION['nofchances'] = $_SESSION['nofchances'] - 1;
echo "You have ".$_SESSION['nofchances']." no of chances to try";
echo "<br>Please try again";
header("location:question.html");
}
else
{
echo "You won the game";
$_SESSION['nofchances']=10; // resetting back
}
}
else
{
echo "Your chances expired";
}
?>
You can call a function in onBlur/onChange
<script>
function test()
{
var count=<?php echo $count;?>;
var guess=parseInt($('#hid_num').val())+1;
if(guess>count)
{
alert('Your chances over!');
}
else
{
$('#hid_num').val(guess);
}
}
</script>
<input type="text" onblur="test();" id="chk_estimate" />
<input type="hidden" value="0" id="hid_num" /></body>
If you dont want to use sessions yet you could define a hidden input field which stores the current try then incriment "+1" it whenever the submit is pressed / the site is reloaded. Something like:
if( isset($_POST['try']) ) {
$try = $_POST['try'];
$try += 1;
} else {
$try = 0;
}
add the hidden field in your form like:
$hiddenTry = '<input type="hidden" value="'. $try .'" name="try"/>';
and add a if clause to when to show the form like:
if ( $try <= 10 ) {
//your form
}
i made this for you i hope it can help you learn something new (i edited it a couple of times to make variable names easier to understand make sure you check it again - i added a cheat also :) )
<?php
session_start(); // with this we can use the array $_SESSION to store values across page views of a user.
mt_srand(time()); // this is to ensure mt_rand function will produce random values. just ignore it for now. it's another story :)
$max_tries = 10; // limit of guesses
$_SESSION['the_magic_number']=!isset($_SESSION['the_magic_number'])?mt_rand(0,100):$_SESSION['the_magic_number'];
// the previous line is a one-liner if then else statement. one-liners works like this:
// $my_name_will_be=($isBoy==true)?"George":"Mary";
if(isset($_POST['num'])) // if this pageview is from a valid POST then...
{
$_SESSION['current_try']=isset($_SESSION['current_try'])?$_SESSION['current_try']+1:1;
// one-line if then else again. This increases the try user is now, or resets it to one
}
?>
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<?php
if ($_SESSION['current_try']<=$max_tries) // if user has more tries available
{
if(intval($_POST['num'])==$_SESSION['the_magic_number']) // did he found it?
{
echo "You found it! Gongratulations! Click <a href=''>here</a> to try again!";
// oh and do not forget to reset the variables (you found this bug, well done!)
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
else
{
// if he didn't found it, display the status of tries left, and the form to try again
echo "This is your try ".($_SESSION['current_try'])." of ".$max_tries." Good Luck!";
?>
<form method="POST" action="mygame.php">
Please enter any number :
<input type="text" name="num"/>
<input type="hidden" name="tries" value="<?php echo (isset($_POST['tries']))?$_POST['tries']-1:$max_tries; ?>"/>
<input type="submit" name="go"/>
</form>
<span style="color:white;background-color:white;"><?php echo "You bloody cheater! The magic number is ".$_SESSION['the_magic_number'];?></span>
<?php
}
}
else
{
// here we are if no tries left! An empty href to reload the page, and we resetting our variables.
// the_magic_number gets NULL so at the start of script it will be "not set" and will get a mt_rand(0,100) value again
echo "You lost! Sorry! Click <a href=''>here</a> to try again!";
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
?>
</body>
</html>
the span at the end is a cheat ;) press ctrl+a to use it !!!

php processing a dynamically generated form

I'm using php to generate an html page that displays blog/thread items, and I am using javascript to show/hide some of the details. The problem is that I am generating unique IDs for each set of hidden content, which contains a form to process the input. In processing the form, I need to know which blog item was edited - I want to use $_POST. I'm pretty new to javascript, and I'm thinking that there is probably a solution I can use there.
I want the post to save the text to the mysql database (so call one of my php functions that I have working) and tell me what the text was and what the threadId is.
Here is the php code snipet, where $threadDetailItem is an array that has my thread data in it.
foreach ($threadData as $threadDetailItem)
{
// display main line (a bunch of code here ...)
// append button to edit or delete the post for admin
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// edit link opens content, and delete pops up a confirmation box
$el = sprintf ("editThreadLink_%d", $threadDetailItem['blogThreadId']);
$ec = sprintf ("editThreadContent_%d", $threadDetailItem['blogThreadId']);
$link1 = sprintf ("<a id=\"%s\" href=\"javascript:toggle('%s', '%s');\">+</a>", $el, $ec, $el);
$msg .= sprintf ("<li id=\"field6\">%s</li>\n", $link1);
}
$msg .= "</ul>\n";
echo $msg;
// now that the row is printed, lets add the hidden content if admin so they can edit
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// hidden content to enable editing of the posting
$msg = sprintf ("<div id=\"%s\" style=\"display: none\">\n", $ec);
echo $msg;
echo "<form name=\"form\" method=\"post\" action=\"\">\n";
$msg = sprintf ("<textarea id=\"%s\" name=\"%s\">%s</textarea>\n",
$ec, $ec, $threadDetailItem['threadTitle']);
echo $msg;
$msg = sprintf ("<button type=\"submit\"> %s</button>\n", $lang->get('BLOG POST'));
echo $msg;
echo "</form>\n";
echo "</div>";
}
}
Suggestions on good ways to handle this event are much appreciated. Thanks in advance.
The fields in the data are: blogThreadId, threadTitle, username, createdOn, lastUpdated, displayed (not used) and threadDetails (array containing the posting information).
I was able to use $_POST along w/ the ID in a hidden field to enable my php scripts to know which thread was being edited. It is working

Categories