Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've a form tag which sends the name for an array to a function but how can I name my array after this? Ok, code says more than thousand words:
<?php
function dynamic($id, $name, ... ){
...
echo "<select id='$id' name='$name' size='...' multiple>";
...
echo "<select id='$id' name='$name'>";
...
}
?>
<form ... method="post">
<p>
<?php
echo dynamic("dynamic1", "choice1", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic2", "choice2", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic3", "choice3", ...);
?>
</p>
<input type="submit" value="send"/>
</form>
I want to create a list where you can select multiple items but for this $name needs ot be an array. The array should named like the second variable. In one case it should be named choice1 in another choice2
Like how do I get from $name = "choice1"; to choice1[]
#edit Added a new line in function to show my problem. somtimes $name needs to be and array and sometimes not
Any ideas?
You are looking to use dynamic variable names, which is possible in PHP, but you need to be careful with this. Production code using this can be difficult to maintain and throw errors quite easily.
Anyway, lets say you have a value in the form $_POST that you want to use as a variable name. You would do so like this.
$id = "gettheidsomewhere";
${$id}[] = "whatever";
Like i said, use this carefully. Dynamic variable names are dangerous and very hard to debug when things break.
If you do not know the value used for $id, then you will need to loop through your post variables and assign them accordingly. I would assume you want to add some extra logic, but here is a basic example.
Using a key value loop you can obtain the name of the post variable, stored as $key and the value. So for $_POST["something"] = "test", when this line is looped over, $key will be "something" and $value will be "test".
foreach ($_POST as $key => $value)
{
${$key}[] = $value;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am sharing my codes below with you. I can save new data as json in my database, but I couldn't figure out how to delete what I want from this data. How should I do?
<?php
include("matta/database.php");
?>
<html>
<meta charset="UTF-8">
<?php
$sorgum = mysql_query("SELECT * FROM birlikler WHERE id = 1", $vtbaglan);
$sorgu = mysql_fetch_array($sorgum);
$uyelerim = $sorgu['uyeler'];
$uyesim = json_decode($uyelerim, true);
foreach($uyesim as $bubirtest){
echo ''.$bubirtest['kullanici'].'<br>';
}
echo ''.$uyebilgileri.'
<form method="post">
<input type="text" name="kullaniciadi" placeholder="kullaniciadi"s>
<input type="text" name="rutbe" placeholder="rutbe">
<input type="text" name="kadi" placeholder="karakteradi">
<button type="submit" name="verigir">verigir</button>
</form>';
if(isset($_POST["verigir"])){
$kullaniciadi = $_POST["kullaniciadi"];
$rutbe = $_POST["rutbe"];
$karakteradi = $_POST["kadi"];
$arr = [
'kullanici' => ''.$kullaniciadi.'',
'rutbe' => ''.$rutbe.'',
'karakteradi' => ''.$karakteradi.''
];
$uyesim[] = $arr;
$arrim = json_encode($uyesim);
//echo '<br>'.$uyeler.','.$arrim.'';
$veriekle = mysql_query("UPDATE birlikler SET uyeler = '$arrim' WHERE id = 1", $vtbaglan);
}
?>
my previous question: PHP MySQL Json data saving
Edit:
I tried the code stated by #gguney but could not reach the result. I leave the "uyeler" column in my database below so that I can clearly explain the way I want.
[{"kullanici":"matta","rutbe":"20","karakteradi":"Vitality_Test"},{"kullanici":"Linuxy","rutbe":"19","karakteradi":"Linuxy_Test"}]
To give an example of the operation I want to do; I want to delete the user whose "kullanici" value is "matta" from this line. In other words, I want the new data that I want to reach as a result of my operation to be as follows;
[{"kullanici":"Linuxy","rutbe":"19","karakteradi":"Linuxy_Test"}]
The PHP version I'm using is a bit old. I'm aware of this, but I have to use this version for my current job. I would be very grateful if you could help.
You can update that json field. Or like any other array field. Just use unset.
For example:
unset($arr['rutbe']);
and use again your update mysql query to delete that field.
Or you can use MySQL JSON_REMOVE function
UPDATE birlikler
SET birlikler.uyeler = JSON_REMOVE(birlikler.uyeler, 'rutbe');
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am having some serious trouble for some reason with creating a basic PhpMyAdmin database and making a page with a scoreboard. There will be a game that you play, and when you're done you can input a score and your name using basic form elements. When you press submit the page will reload and you will be able to see the top ten scores, ranked by highest first.
My issue is that I have no idea where to start with this. I have just started Php and don't wish for anything crazy. I have the ~/php/db_connect.php set up correctly already; I just need to make the function work.
How do you recommend I go through with this? Example code is extremely helpful.
I know the first response is "what have you tried?" and I haven't tried much.
This is what I have right now:
// define variables and set to $name = $myArray[0];
$babyinfo = fgets($myfile);
$myfile = scoreboard-dk;
$myArray = explode(',', );
$score = $myArray[1];
$name = $myArray[2];
$insertStmt = "INSERT INTO scoreboard-dk ('score','name') VALUES ('$score','$name')";
// Inserting Babynames into database
$db->query($insertStmt);
?>
<form action=" $db;?>" method="post">
Name: <input type="text" name="name" value=" echo $name;?>" required><br>
Score: <input type="text" name="score-dk" value=" echo $score;?>" required><br>
<input class="btn btn-primary" type="submit">
</form>
<tr> <th scope=row> echo $i;?></th> <td> echo $score;?></td> <td> echo $name;?></td> <td> echo $votes;?></td> </tr>
Thanks in advance.
Ok. First some mistakes you made:
$myfile = scoreboard-dk; isn't working. This way it would be a constant. You need the "$" or quotation marks if it should be a string.
$myArray = explode(',', ); I don't know what you want to do? The second argument is missing. This statement won't work. Second argument has to be a string.
You have to properly escape the query before executing the statement.
You can do this by replacing the following line before building the string:
$score = $db->real_escape_string($myArray[1]);
$name = $db->real_escape_string($myArray[2]);
Furthermore are you sure you use the correct indices for the array access? Counting starts with 0, not with 1.
You can't use PHP code without the opening tags. I thought that you cut that away at the start of the file. You always have to open PHP code blocks with
Perhaps you should search for example code elsewhere. I think stack is more for specific questions. But the code actually shows that you lack of some basic knowledge ... no offense.
The reason people can't help you is that your question is way too broad and everyone will have a different approach about how to implement it.
That being said, here is the pseudo code I would use to implement this. It can be done in a single file. Good luck!
File: score_keeper.php
<?php
error_msg = array
if (form submitted)
$name = name from form
$score = score from form
// Do validation to ensure name and score is as expected.
if name is empty
error_msg[] = 'Name cannot be empty'
if score is not numeric
error_msg[] = 'Score must be numeric'
if empty(error_msg)
// INSERT
// Make sure you use parameterized queries
SQL = INSERT into table (name, score) VALUE (?, ?)
end-if
end-if
// READ top 10
SQL = SELECT name, score FROM table WHERE ...
if !empty(error_msg)
show error_msg
?>
<form method="post">
<input name="name">
<input name="score">
</form>
HTML table
<?php
// output top 10 results
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make a form in html that would create radio options bases upon the specified array in PHP.
Code:
<form name="form" action="Test.php" method="get">
<?php
//Creates the Array
$radioButtonArray = array("cat", "dog", "sheep", "moose");
//Length of the Array
$count = count($radioButtonArray);
//Runs for each index.
for($x = 0; $x < $count; $x++)
//Creates a radio button with the specified length
echo "<input=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
?>
</form>
As you can see firstly I open the form tag inside of HTML. Then I create a array with animals names and run a loop through each array index. During each loop it should create a new radio button and then make a new line as directed by the echo.
The issue is that when I run the file the output should be for example:
(RADIO BUTTON HERE) cat
(RADIO BUTTON HERE) dog
(RADIO BUTTON HERE) sheep
(RADIO BUTTON HERE) moose
Instead I get:
cat
dog
sheep
moose
I know that it is reading the echo line so the error would have to be located on that line. I am very new to PHP and decently familiar with HTML so a simple but detailed explanation of what I did wrong or what I should do would be very greatly appreciated. Thank you in advance.
How to Fix:
I did not correctly enter the format for declaring a input.
//Change This
echo "<input=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]}<br>";
//To This
echo "<input type=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]}<br>";
There is small error on the echo statement. HTML radio button should read
but your output statement reads instead.
Hence you should change
echo "<input=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
To
echo "<input type=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
Try this:
echo "<input type=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
You are not specifying the input type.
input=\"radio\" should be input type=\"radio\"
It should be input type="radio" not input="radio"
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is my HTML Code
<input type="checkbox" value="fotoğraf" name="materyal[]"> Fotoğraf
<input type="checkbox" value="resim" name="materyal[]">Resim
<input type="checkbox" value="çizelge" name="materyal[]">Çizelge
<input type="checkbox" value="katlanabilir harita" name="materyal[]"> Katlanabilir Harita
There are checkbox and i'll take values with $_POST['materyal'] and then i want to write screen values with comma if values more than one. if checkbox values empty i don't write anything screen.
if (isset($_POST['materyal']) && !empty($_POST['materyal'])) {
$materyal = $_POST['materyal'];
echo "İçerdiği extra materyaller ; ";
foreach ($materyal as $materyallist) {
foreach ($materyallist as $yenimateryal){
array_push($sonmateryal, $yenimateryal);
}
}
echo implode(", ", $sonmateryal);
}
This is my code. when i want to use implode in if contiditon, I take mistake.
How can i do
It seems like you just want to show the contents?
$sonmateryal = array();
if (isset($_POST['materyal']) && !empty($_POST['materyal'])) {
echo "İçerdiği extra materyaller ; ";
foreach ($_POST['materyal'] as $materyallist) {
foreach ($materyallist as $yenimateryal) {
$sonmateryal[] = $yenimateryal;
}
}
}
echo implode(", ", $sonmateryal);
update according to given HTML
if (!empty($_POST['materyal'])) {
echo "İçerdiği extra materyaller ; ".htmlentities(implode(',', $_POST['materyal']));
}
Since you're posting the inputs as simple array's this will implode the results with a comma if the post-ed value isn't empty..
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a special form I have been making that uses some cusotm post types in wordpress. At one point I need to echo a variable $i into an if statement.
There is some validation stuff at the top that will look like this and the code in the loop is below. Pretty much I have been trying to get the majorCause1Error to be majorCause $i Error if you know what I mean, so all up it will be like 1-13
Edit: Sorry If it is hard to see what I am asking, I am finding it really hard to word my problem.
So there is a loop running around the li tags and it echos $i into the name etc so it becomes majorCause1 then next one majorCause2 and the next one magjorCause3 etc etc
Under the labels there is an if statement that is like - if($majorCause1Error !='') { do something } - I want this to be like if($majorCause1Error !=''){} and then the next one be like if($majorCause2Error !=''){} and then if($majorCause3Error !=''){}
Does this make more sense?
Here is a link to the site http://www.foresightaus.com.au/form/
if(trim($_POST['majorCause1']) === '') {
$majorCause1Error = "Please enter a major cause.";
$hasError = true;
} else {
$majorCause1 = trim($_POST['majorCause1']);
}
if(trim($_POST['majorCause2']) === '') {
$majorCause2Error = "Please enter a major cause.";
$hasError = true;
} else {
$majorCause2 = trim($_POST['majorCause2']);
}
<li class="fill-in">
<label for="majorCause<?php echo($i); ?>"><?php echo($j); ?>. State one major cause:</label>
<input type="text" name="majorCause<?php echo($i); ?>" id="majorCause<?php echo($i); ?>" value=""/>
<?php if($majorCause1Error != '') { ?>
<span class="error"><?=$majorCause1Error;?></span>
<?php } ?>
</li>
You probably want to be using an array but what you are referencing is called a variable variable and is supported by PHP!
Something like this should do it
${"majorCause{$i}Error"}