I've found myself with the following problem: I have form with a random number of fields. (This is so users can enter their fellow team members's names -- and there's no set size for teams.) I need this inputted data to be formatted in preparation for being stored in a database.
The database structure is fine, it's just getting a random number of $_POSTs and putting them into an array that's the issue.
So far I've got some javascript that allows the user to create/remove an infinite number of fields, with incrementing ids/names (e.g. TeamMemberName1, TeamMemberEmail1, TeamMemberName2, TeamMemberEmail2, etc.).
Right now I've created an ugly series of PHP statements that puts a reasonable amount of POSTed data into a multidimenional array -- I don't see why a team should ever be bigger than 50 -- and then I was going to process the array to remove any blank rows before passing it onto the database.
Example:
$submittedTeamMembers =
array ( "teamMember1" =>
array ( "name" => $_POST["teamMemberName1"],
"email" => $_POST["teamMemberEmail1"])
);
But I'm guessing there's a better way!
Your input names can be in array form, which PHP will understand perfectly. Example:
<input type="text" name="teamMembers[0]['name']" />
<input type="text" name="teamMembers[0]['email']" />
which PHP will interpret after post as you'd expect:
//print_r($_POST['teamMembers']);
Array
(
[0] => Array
(
[name] => foo
[email] => bar
)
)
Just give all your fields a name of 'TeamMemberName[]' or 'TeamMemberEmail[]'. Each should be posted regardless of whether or not the value is there, so they should always match up.
This will pass them as an array to your server-side PHP script, so you can access them like so:
$teamMemberNames = $_POST["teamMemberName"];
$teamMemberEmails = $_POST["teamMemberEmail"];
for ($i = 0; $i < count($teamMemberNames); $i++)
echo "name = {$teamMemberNames[$i]}, email = {$teamMemberEmails[$i]}\n";
Related
i need to know how i can have a array with the rand function show up lets say a email and a password in two different text areas how would i do this
this is what ive already tried but keeps giving me string number instead of detail
index.php:
include "details.php";
$gen=array_rand($test);
$stock=count($test);
<form method='post' action='free.php'>
<b>Email:</b><textarea name="email"><?php echo "$gen";?></textarea><br>
<b>Password:</b><textarea name="password"><?php echo "$gen";?></textarea>
<center>
<button type="submit">Generate</button><br>
stock:<?php echo "$stock";?>
</center>
</form>
details.php
$test = [
['account' => 'acc1','pass' => 'pass1'],
['account' => 'acc2', 'pass' => 'pass2']
];
project link:
http://noxxeraltgen.tk/minecraft/free.php
array_rand() returns an index and not the actual array element. From the manual...
Return Values
When picking only one entry, array_rand() returns the
key for a random entry. Otherwise, an array of keys for the random
entries is returned. This is done so that random keys can be picked
from the array as well as random values. Trying to pick more elements
than there are in the array will result in an E_WARNING level error,
and NULL will be returned.
You also need to specify the part of the array you want to output for each item, so...
echo "$gen";
Should be either
<?php echo $test[$gen]['account'];?>
or
<?php echo $test[$gen]['pass'];?>
My POST form sends a value &messages=12,11
I get it using: $messages = $ep->remove($_POST["messages"]);
And my SQL string is:
$query = $db->prepare("DELETE FROM messages WHERE messageID IN ('".$messages."') AND accountID=:accountID");
$query->execute([':accountID' => $accountID]);
And the error appears....
<b>Fatal error</b>: Uncaught exception 'PDOException' with message 'SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '12,11'' in /var/www/vhosts/xxx.xxx/xx/xxx/xx/xxxx/messages.php:17
This code deletes multiple messages from the database. But don't works for me. Any fix?
Remove the quotation marks:
$query = $db->prepare("DELETE FROM messages WHERE messageID IN (".$messages.") AND accountID=:accountID");
Otherwise the value you're sending is 12,11 (which isn't a number as per your database definition), as opposed to 12 and 11, which are both numbers.
Finally, this particular query structure is open to SQL injection. You may want to either sanitise the $messages variable (since it can only include numbers), or create a prepared statement.
For this example, sanitising could work as follows:
$messages = preg_replace('/[^0-9,]/', '', $messages);
//Removes all characters besides numbers and commas
You could also ensure that the list of numeric message IDs always matches the following regex pattern:
$\d+(?:,\d+)*$
That is, the parameter should always be some number, followed by an optional quantity of ,\d+ terms
if (!preg_match("/^\d+(?:,\d+)*$/", $messages)) {
// throw an exception, you are being injected
}
Just to add to the other answer, here is a way to properly prepare all the values
$array = explode(',', '1,2,3,4,5,6');
$keys = preg_replace('/(.+)/', ':v\1', array_keys($array));
print_r($keys);
$sql = "DELETE FROM messages WHERE messageID IN ( ".implode(',', $keys)." ) AND accountID=:accountID";
print_r($sql);
$params = array_combine($keys,$array);
$params['accountID'] = 'foo';
print_r($params);
//$stmt->execute($params);
Output
//print_r($keys);
Array
(
[0] => :v0
[1] => :v1
[2] => :v2
[3] => :v3
[4] => :v4
[5] => :v5
)
//print_r($sql);
DELETE FROM messages WHERE messageID IN ( :v0,:v1,:v2,:v3,:v4,:v5 ) AND accountID=:accountID
//print_r($params);
Array
(
[:v0] => 1
[:v1] => 2
[:v2] => 3
[:v3] => 4
[:v4] => 5
[:v5] => 6
[accountID] => foo
)
Sandbox
It was way too much for a comment.
Basically it takes the keys and using preg replace we can take the sequential number and add a string to it (placeholders have to start with a alpha). Technically the : in the array for execute is optional.
Then we can put that into the query, as it's all generated by PHP because the keys are made from explode. If you have keys from POST, don't use those instead use array_keys(array_values($array)) array values will make the array numerically indexed, then you use those keys.
Next using array combine we can merge those keys back into the original values and put that array into execute
In this case You can do it just with a regex, but I wanted to show something that was useful for more complex cases of IN.
asking for insert multiple lines in one mysql column (with something like line break like show didn't mean inserting data in multiple rows have multiple variables contain different urls like
$var_one = "http://example.com";
$var_two = "http://example.org";
$var_two = "http://example.net";
want to store these values in one mysql column ever value should be in new line refer image describe better
asking for insert multiple lines in one mysql column (with something like line break like didn't mean inserting data in multiple rows
If you trying in php, then you can serialize the data and store as single column in DB.
While retriving data, we can unserialize and get the data as array. Find below example.
<?php
$var = array();
$var[0] = "http://example.com";
$var[1] = "http://example.org";
$var = array("1","2","3");
print_r($var); // Array ( [0] => http://example.com [1] => http://example.org )
$b=serialize($var);
echo $b; // a:2:{i:0;s:18:"http://example.com";i:1;s:18:"http://example.org";}
$c=unserialize($b);
print_r($c); // Array ( [0] => http://example.com [1] => http://example.org )
So I am currently trying to extract information from a json array using json_decode($result,true). The background here is that there is another php script getting information from a database and it is sending the data to me as json_encoded result.
using print_r($json) i get the following
Array
(
[result] => 1
[message] => Query Successful
[data] => Query Output
[0] => Array
(
//Several values
[test] => test
[Example] => catcatcat
[choice2] => B
)
[1] => Array
[test]=> test
//etc....
I understand we can use a simple for loop to get some stuff to display or in this case I used
for($i=0;$i<=count($json); $i++){
echo $json[$i]['test'];
//etc etc
}
and that will display the value. But what I cant figure out is how to send that to my HTML page as an output as a list.
I am trying to get it to display as following
Test catcatcat B
Test etc etc
--This may be a separate question but for me to learn I want to know if it's possible to actually break down the array and send to html as radio input and turn it into a value to choose from.
Your JSON result is a mixture of 1st level elements and sub-arrays, so you'll need to filter those.
Use a foreach loop like this to output radio buttons:
foreach($json as $current) {
if(!is_array($current))
continue; // skip top level properties that aren't sub arrays
echo '<input type="radio" name="yourradio" value="' . $current['choice2'] . '"> ' . $current['test'] . ' ' . $current['Example'];
}
The value of the radio button and the labels are up to you, but that's the general idea.
I have the following PHP code:
$testMessage = "TESTMESSAGE";
$db = new SQLite3('messages.sq3');
$db->exec('CREATE TABLE messages(id INTEGER PRIMARY KEY, message CHAR(255));');
$db->exec("INSERT INTO messages (message) VALUES ('$testMessage');");
$results = $db->query('SELECT * FROM messages ORDER BY id DESC LIMIT 5');
while ($row = $results->fetchArray()) {
print_r($row);
}
The resulting print_r:
Array ( [0] => 1 [id] => 1 [1] => TESTMESSAGE [message] => TESTMESSAGE )
Why is this data duplicated? Is this just the way the array is presented or are there really two copies of TESTMESSAGE string? Inspecting the sqlite file, I only see one actually stored there. I am trying to serialize the output via JSON and this duplication is carrying through to the serialization.
The default is to have the data with both numeric and string keys, merged in the same array.
You need to use $results->fetchArray(SQLITE3_NUM) or $results->fetchArray(SQLITE3_ASSOC) to get numeric and string keys respectively. The default is SQLITE3_BOTH, which I've always hated.
Both $row[1] and $row['message'] will give you the same data. This is because on technique uses the numerical index of the column and the other uses the name. They are both included in the column so that you can use either way to access them. It does not indicate any sort of duplication in the database itself.
Here you can see the documentation and how to tell PHP which version you want. By default it gives you both: http://php.net/manual/en/sqlite3result.fetcharray.php