I submitted a question yesterday but I think it was too long and confusing. Today I shortened everything and submitting an example of my code. The idea behind the code is to parse content, insert the content into a form which will be either echoed in this example or inserted into mysql database. The code works with no errors but show only individual letter and digits instead of full words, please see details below:
<?php
$fullstring = "Name: Steve - Age: 25, Name: Bob - Age: 30, Name: Amanda - Age: 18,"; // Content to be parsed
function get_string_between($string, $start, $end) {
$start = preg_quote($start);
$end = preg_quote($end);
$pattern = "~$start\s*(.*?)$end\s*~";
$match = preg_match_all($pattern, $string, $matches);
if ($match) {
return $matches[1];
}
}
$parsed1 = get_string_between($fullstring, "Name: ", "-");
$parsed2 = get_string_between($fullstring, "Age: ", ",");
////////// The form //////////////////////
echo '<form action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) {
echo "Name: <input name=\"name\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type: <input name=\"age\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}
echo '<input type="submit" name="submit" value="submit">';
echo '</form>';
if (isset($_POST['submit'])) {
$i = 0;
foreach ($_POST as $value) {
$name = $_POST['name'][$i];
$age = $_POST['age'][$i];
echo $name.'....'.$age.'<br>';
$i++;
}
}
//// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
//////////////////////////////////////////////////////////////
?>
When I press submit I get this echoed:
A....1
m....8
a....
Instead of of all the names in the in the form.
I appreciate all the help thank you all.
You can use name[] and age[]
echo '<form action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) {
echo "Name: <input name=\"name[]\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type: <input name=\"age[]\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}
echo '<input type="submit" name="submit" value="submit">';
echo '</form>';
if (isset($_POST['submit'])) {
foreach($_POST['name'] as $k=>$name){
echo $name.'.... Age:'. $_POST['age'][$k];
}
}
Try this: It is tested:
$fullstring = "Name: Steve - Age: 25, Name: Bob - Age: 30, Name: Amanda - Age: 18,"; // Content to be parsed
function get_string_between($string, $start, $end) {
$start = preg_quote($start);
$end = preg_quote($end);
$pattern = "~$start\s*(.*?)$end\s*~";
$match = preg_match_all($pattern, $string, $matches);
if ($match) {
return $matches[1];
}
}
$parsed1 = get_string_between($fullstring, "Name: ", "-");
$parsed2 = get_string_between($fullstring, "Age: ", ",");
echo '<form action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) {
echo "Name: <input name=\"name{$i}\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type: <input name=\"age{$i}\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}
echo '<input type="submit" name="submit" value="submit">';
echo '</form>';
if (isset($_POST['submit'])) {
$i = 0;
while ($i < count($parsed1)) {
$name = $_POST['name'.$i];
$age = $_POST['age'.$i];
echo $name.'....'.$age.'<br>';
$i++;
}
}
Your problem is in these lines:
$name = $_POST['name'][$i];
$age = $_POST['age'][$i];
You are getting the character at index $i from each $_POST key. Just delete the [$i] in each of these lines, and your output should become
Ama....18
Ama....18
Note that there is no need to have this in a loop -- you are effectively doing this output twice due to the foreach.
Related
OK let me be as specific as possible.... I would like to change the way my search bar behaves. Right now the string has to match the MySQL query exactly!!! or it won't show my products.
Here is what I got:
A search for "case iphone"
searchitems.php?tosearch=case+iphone&Search=Search
Now a search for "iphone case"
searchitems.php?tosearch=iphone+case&Search=Search
Now based on how the query would work...if I type in the URL manually to this... it works how I want it to:
searchitems.php?tosearch=%iphone%&%case%&Search=Search
So how do I go about changing the URL from
searchitems.php?tosearch=case+iphone&Search=Search
to
searchitems.php?tosearch=%iphone%&%case%&Search=Search
Here is the code that I have so far:
Search Form In index.php
<form method="GET" action="searchitems.php">
<input size="50" type="text" name="tosearch" value="Search" name="keyword" id="keyword" title="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field">
<input type="submit" name="Search" value="Search" alt="Search" id="searchbutton" title="Search" class="sub_btn">
</form>
searchitems.php (Sorry if it isn't tabbed correctly just copied and pasted)
<?php
include('core/header2.php');
include ('core/connectdb.php');
if(isset($_GET['tosearch'])) {
$tosearch=$_GET['tosearch'];
$tosearch=urldecode($tosearch);
$tosearch = preg_replace('!\s+!', ' ', trim($tosearch));
$search_terms = explode(' ',$tosearch);
$search_terms[] = $tosearch;
$search_terms=array_unique($search_terms);
$query = "select * from products where ";
$query_fields = Array();
$sql = "SHOW COLUMNS FROM products";
$columnlist = $connect->query($sql);
while($arr = $columnlist->fetch_assoc()){
extract($arr);
$query_fields[] = $Field . " LIKE ('%". $tosearch . "%')";
}
$query .= implode(" OR ", $query_fields);
$results = mysqli_query($connect, $query) or die(mysql_error());
$rows = $results->num_rows;
if ($rows > 0) {
$cols = 5;
$counter = 1;
$nbsp = $cols - ($rows % $cols);
echo '<div id="content" class="float_r">';
echo "<table border=\"0\">";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<tr align="center">';
}
extract($row);
echo '<td valign="top" style="padding-right:15px;">';
echo "<a href=itemdetails.php?itemcode=$item_code>";
echo '<img src=' . $imagename . ' style="max-width:120px;max-height:140px;
width:auto;height:auto;"></img><br/>';
echo $item_name .'<br/>';
echo "</a>";
echo '<div class="product_price">$'. $price .'</div>';
echo "<form method=\"POST\" action=\"cart.php?action=add&icode=$item_code&iname=$item_name&iprice=$price&ilocation=$location\">";
echo "<input type=\"submit\" name=\"addtocart\" value=\"Add To Cart\"></form>";
echo "</td>";
if(($counter % $cols) == 0 ){
echo "</tr>";
}
$counter++;
}
if($nbsp > 0) { // Add unused column in last row
for ($i = 0; $i < $nbsp; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
}
}
echo '</table></div><div class="cleaner"></div>';
include('core/footer.php');
?>
well, brother, it's a bad approach how you doing it. But for learning, its fine. For + sign issue, you can use php urldecode, example:
<?php
$tosearch = 'a+b';
echo urldecode($tosearch);
it has its own pro/con thing but on high-level it will work for you, you can dig more into it if you like.
My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>
I'm studying a way to use the Google Books API.
Using this code have the expected result.
$page = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=julio+verne&maxResults=40");
$data = json_decode($page, true);
for($a = 0 ; $a <= 39 ; $a++) {
$img = $data['items'][$a]['volumeInfo']['imageLinks']['thumbnail'];
print '<img src="'.$img.'" alt="ScanLine"/>';
echo '<br>';
echo "Title = " . $data['items'][$a]['volumeInfo']['title'];
echo '<br>';
echo "Authors = " . #implode(",", $data['items'][$a]['volumeInfo']['authors']);
echo '<br>';
echo "Editora = " . $data['items'][$a]['volumeInfo']['publisher'];
echo '<br>';
echo "id = " . $data['items'][$a]['id'];
echo '<br>';
echo "Resumo = ";
echo "<p>" . $data['items'][$a]['volumeInfo']['description'];
echo '</p><br>';
}
On the other hand, implementing and using the code form the code does not work.
My page with form have this code:
<form action="action.php" method="POST">
<div class="form-group">
<div class="campos">
<label>
Search
</label>
<input type="text" name="search" style="margin-right: 10px; width:250px; float:left" class="input-field" placeholder="Title, Author..." />
<input type=hidden name=numResults value="&maxResults=40">
<button type="submit" id="search" class="btn btn-default">Search</button>
</div>
</div>
</form>
And my action have this code:
$var1 = "https://www.googleapis.com/books/v1/volumes?q=";
$var2 = urlencode($_POST['search']);
$var3 = "&maxResults=40";
$str = str_replace(" ", "+", $var2);
$page = $var1.$str.$var3;
$data = json_decode($page, true);
echo $page;
echo '<br>';
for($a = 0 ; $a <= 39 ; $a++) {
$img = $data['items'][$a]['volumeInfo']['imageLinks']['thumbnail'];
print '<img src="'.$img.'" alt="ScanLine"/>';
echo '<br>';
echo "Title = " . $data['items'][$a]['volumeInfo']['title'];
echo '<br>';
echo "Authors = " . #implode(",", $data['items'][$a]['volumeInfo']['authors']);
echo '<br>';
echo "Editora = " . $data['items'][$a]['volumeInfo']['publisher'];
echo '<br>';
echo "Resumo = ";
echo "<p>" . $data['items'][$a]['volumeInfo']['description'];
echo '</p><br>';
}
What must be wrong?
Any advise?
Thanks from Brazil
You are not calling file_get_contents() in the second example. So $page is just the url.
$page = file_get_contents($var1.$str.$var3);
I have a form with a loop inside.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
for ($i = 1; $i <= 2; $i++) {
echo "Numero ";
echo $i;
echo "<input type='text' name='number2[$i]' id='number2{$i}' />";
}
?>
<input type="submit" name="submitbutton" value="Confirm!">
</form>
<?php
print_r( $_POST );
if(!isset($submitbutton)) {
if (isset($_POST['number2']) != "") {
echo "<b>{$_POST['number2']}</b>, !\n";
$nI = $_POST['number2'];
}
}
?>
The output I get is:
Array ( [number2] => Array ( [1] => 3 [2] => 4 ) [submitbutton] => Confirm! ) Array, !
I would like to know how can I put the number in a session.
For example Session[1]=3, Session[2]=4
I try with array and foreach but I always get error.
Something like this should work for you:
<?php
// Start a PHP Session
session_start();
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
for ($i = 1; $i <= 2; $i++) {
echo "Numero ";
echo $i;
echo "<input type='text' name='number2[$i]' id='number2{$i}' />";
}
?>
<input type="submit" name="submitbutton" value="Confirm!">
</form>
<?php
// If the form was submitted and number2 is an array
if(isset($_POST['submitbutton'])
&& isset($_POST['number2'])
&& is_array($_POST['number2'])) {
// Loop through each posted value and save it to the session
foreach ($_POST['number2'] as $key => $value) {
$_SESSION["number2_{$key}"] = $value;
}
}
echo "number2_1 = " . $_SESSION["number2_1"] . "<br />";
echo "number2_2 = " . $_SESSION["number2_2"] . "<br />";
?>
What error are you getting? Note that isset() merely returns TRUE or FALSE, so isset($_POST['number2']) will never equal the empty string.
Here's the form handling
if(isset($_POST['clear'])) {
mysql_query("DELETE FROM md5dictionary");
}
if(isset($_POST['submit'])) {
if(strlen($_POST['keywords']) < 1 || ctype_space($_POST['keywords']) == true) {
$errors['blank'] = "<span class='error'> Please insert a word </span>";
} else {
$newword = $_POST['keywords'];
$db_checkExist = mysql_query('SELECT * FROM md5dictionary WHERE keywords="' . $newword . '"');
echo mysql_num_rows($db_checkExist) . "<br />";
if(mysql_num_rows($db_checkExist) > 0) {
echo "outside else " . mysql_num_rows($db_checkExist);
$finalResult = "<span class='error'> Failed!!! </span>";
} else {
echo "inside else " . mysql_num_rows($db_checkExist);
$md51 = md5($newword);
$md52 = md5($md51);
mysql_query('INSERT INTO md5dictionary(keywords, mdFive, mdFive2) VALUES ("' . $newword . '", "' . $md51 . '", "' . $md52 . '")');
$finalResult = "<span class='success'> Thank you! Wanna add another one? </span>";
}
}
}
Here's the form
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<fieldset> Input Form </fieldset>
<label for="keywords"> Input new Keywords into dictionary: </label>
<?php echo $finalResult; ?>
<?php echo $errors['blank']; ?>
<input name="keywords" type="text" />
<input name="submit" type="submit" value="Add!!" />
<input name="clear" type="submit" value="Clear Database" />
</form>
<h1> Datas: </h1>
<?php
$result = mysql_query("SELECT * FROM md5dictionary");
$rows = mysql_num_rows($result);
for ($i = 0; $i < $rows; ++$i) {
echo "Data " . $i . "<br />";
echo "keywords: " . mysql_result($result, $i, "keywords") . "<br />";
echo "md5: " . mysql_result($result, $i, "mdFive") . "<br />";
echo "md5_2: " . mysql_result($result, $i, "mdFive2") . "<br />";
}
?>
Here's the result: http://md5dictionary.hoangminhdat.com
Question: Why it keeps saying "Failed!" Why it has successfully insert information into my database?
There should be no spelling mistake
I know it will be time-consuming go through my dumb question but plss, i can't explain it myself!!
I've tested the weblink you provided.
If I insert a word then I get 'inside else' and it looks like it's inserted.
If I quickly enter this word again then I get 'failed'.
So I see no problem, isn't this what you want to achieve ?
Otherwise please rethink your question and refine what is not working for you and when.
EDIT:
If you want the successful message then you need another:
echo $finalResult;
after you defined $finalResult.
I'm not sure about what you mean when you say it inserts and it gives "fail".
Do you actually mean "INSERT INTO md5dictionary..." is executed, AND you have the " Failed!!! " code showing?
If this is so, I recommend you investiguate and revise your form flows since it is most probable that calling itself, the form tries to run twice, the second time having null values.
This is what I coming up with.
Have a good day,
S.