I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0
Related
I'm working on in_array() method. If the value read is already in the array it should be skipped and proceed to the next value. If the current value is not on the array yet, it should be pushed to the array.
here's my code:
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$Res_Array = array();
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Problem: It seems that it ignores my condition which is if(in_array($SQL_Result_Time, $Res_Array, true)){break; } and still inserts the value into the array. It still duplicates data
Question:
How to prevent the duplication data where if the current value was found inside the array it would just skip the statement and proceed to another value for checking the array and so on?
Is my logic on checking the value on the array is right?
You are re-initialising your array on every iteration of the while loop. You should declare it outside of the loop:
$Res_Array = array();
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Also, as mentioned by Marvin Fischer in his answer, your break statement will terminate the while loop on the first duplicated value. You should instead use continue
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
...
if(in_array($SQL_Result_Time, $Res_Array, true)){
continue;
}
....
}
This question should clarify any issues you have with break and continue statements
First of all, inside of a loop you should use continue, otherwise you cancel the whole loop, secondly you empty $Res_Array at the beginning of every loop purging the old data, inserting the new one and echoing it again
I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped
I seem to have looked everywhere for this.
Here is the code i use to set a variable to a piece of data from a MySQL database
$PartNo=mysql_result($result,$i,"PartNo");
Where
$result = mysql_query("SELECT * FROM PriceList");
$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name
I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:
$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");
But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)
$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");
foreach ($nDatabaseVars as $X) {
$$X=mysql_result($result,$i,'$X');
}
I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")
If I echo it out instead:
foreach ($nDatabaseVars as $X) {
echo "$$X=mysql_result($result,$i,'$X')";
}
I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.
You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:
$$X=mysql_result($result, $i, $X);
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.
$$X=mysql_result($result,$i,"$X");
I have a cookie which I'm trying to split. The cookie is in this format:
key = val1,val2,val3 (where each value is separated by commas)
is there a way for me to split this in a loop so that I can directly access val3?
I've tried using the explode() function with no success.
for ($i = 0; $i < count($_COOKIE); $i++)
{
$ind = key($_COOKIE);
$data = $_COOKIE[$ind];
//I try and slit the cookie here
$cookie_temp = explode(",",$_COOKIE[$ind]);
//Here is where I wanted to display Val3 from the cookie
print $cookie_temp[2];
next($_COOKIE);
}
my code works fine but I then end up with all my Val3 in a large array. For example, my val3's are numbers and they get put in an array. Can I split this even further?
First of all, I'm hoping you know the name of the cookie you're trying to get the value of. Let's call it mycookie in the rest of my answer.
Second, just scrap the whole loop thing and just access $_COOKIE['mycookie'] directly.
Then, you can now call explode(",",$_COOKIE['mycookie']) to get the separate values.
Next, just get index 2 with [2] as you are in your current code.
As a shortcut, if the second one is the only one you need:
list(,,$val) = explode(",",$_COOKIE['mycookie']);
Assuming you are looping because you have multiple comma-separated cookie key/value groups, use a foreach() instead and with list() you can retrieve the third value with a direct assignment.
foreach ($_COOKIE as $key=>$value) {
list($v1, $v2, $v3) = explode("," $value);
echo $v3;
}
If you have only one cookie value to access, there is no need for the loop, and you can directly call explode(",", $_COOKIE['key'])
PHP 5.4 allows array dereferencing, whereby you can directly access the array element off of the explode() call, but this won't work in earlier PHP versions.
echo explode(",", $_COOKIE['key'])[2];
I need to truncate string and rewrite it back to array
I have got a function where I get data from data base
$data['about_text_list'] = $this->about_text_model->get_array();
I get these fields from data base : id, num, header, text, language
I need to strip_tags and truncate text with function word_limiter
foreach ($data['about_text_list'] as $items)
{
$data['about_text_list']['text'] = word_limiter($items['text'], 100);
$data['about_text_list']['text'] = strip_tags($items['text']);
}
in view I do foreach
<? foreach ($about_text_list as $line) : ?>
<td><?=$line['text']?></td>
<? endforeach; ?>
But I get error, please tell me how to do correct things like this...
In the loop in your controller, you're limiting the word count, then setting that to the value in the array. Then, you're overwriting that value with the strip_tags function. You're using both functions on the same value instead of using the altered values. (And I would strip the tags first, then limit the word count.)
You're also just overwriting the $data['about_text_list']['text'] value each iteration. I'm assuming this needs to be an array of 'text' values? I would create a new array with the updated content and merge your $data['about_text_list'] array with the new array.
Change that loop to this:
$newarray = array();
foreach ($data['about_text_list'] as $key => $value)
{
$item_text = $value['text'];
$altered = strip_tags($item_text);
$newarray[$key]['text'] = word_limiter($altered, 100);
}
$data['about_text_list'] = array_merge($data['about_text_list'], $newarray);
// here, you create a new empty array,
// then loop through the array getting key and value of each item
// then cache the 'text' value in a variable
// then strip the tags from the text key in that item
// then create a new array that mirrors the original array and set
// that to the limited word count
// then, after the loop is finished, merge the original and altered arrays
// the altered array values will override the original values
Also, I'm not sure what your error is (as you haven't told us), but make sure you're loading the text helper to give you access to the word_limiter function:
$this->load->helper('text');
Of course, this all depends on the structure of your array, which I'm guessing at right now.