I have this system where I store checkbox data into an array. So if it is checked it will put the value in the array. Let's say that there are 6 checkboxes, and I check the last 3, then array values [3][4] and [5] will have values, correct? Ok.
Now if the array values [0][1] and [2] are 0 as they haven’t been checked, what is their value?
The question is, that when I do a MySQL insert to a database and I use this code?
mysqli_query($con,"INSERT INTO accounts (chk1, chk2, chk3, chk4, chk5, chk6) VALUES ('$checkbox[0]', '$checkbox[1]', '$checkbox[2]', '$checkbox[3]', '$checkbox[4]', '$checkbox[5]'");
Now, when that query executes, if the first arrays are nothing, it will skip them and pretend they are not there. Is there a way I can make them just put 0 if they haven’t been checked.
Why not just apply a DEFAULT 0 constraint to every check{n} field, in the database?
That way, (1) you will make your data protect themselves regardless of the interface and (2) there would be less code to be written, since less checks would be necessary.
put this code before your query
$checkbox[0]=(isset($checkbox[0]))?$checkbox[0]:0;
$checkbox[1]=(isset($checkbox[1]))?$checkbox[1]:0;
$checkbox[2]=(isset($checkbox[2]))?$checkbox[2]:0;
$checkbox[3]=(isset($checkbox[3]))?$checkbox[3]:0;
$checkbox[4]=(isset($checkbox[4]))?$checkbox[4]:0;
$checkbox[5]=(isset($checkbox[5]))?$checkbox[5]:0;
OR
// get $_POST value
function initPostValue($elementVar, $defVal=null) {
if(!isset($_POST[$elementVar])){
$_POST[$elementVar] = $defVal;
}
return $_POST[$elementVar];
}
// get $_REQUEST value
function initRequestValue($elementVar, $defVal=null) {
if(!isset($_REQUEST[$elementVar])){
$_REQUEST[$elementVar] = $defVal;
}
return $_REQUEST[$elementVar];
}
// get $_GET value
function initGetValue($elementVar, $defVal=null) {
if(!isset($_GET[$elementVar])){
$_GET[$elementVar] = $defVal;
}
return $_GET[$elementVar];
}
Example : $checkbox[0] = initRequestValue('checkbox[0]',0);
use above function for get any value take from $_GET,$_POST,$_REQUEST so there are no need to for check empty
if(!isset($checkbox[1]))
$checkbox[1]=0;
They will not have values.
You also want to sanity check them using mysqli_real_escape_string.
I'd do an isset on each checkbox item and set it to 0 if it's not there.
Code example as requested:
$checkbox[0] = isset($_REQUEST['checkboxName']) ? mysql_real_escape_string($_REQUEST[$_REQUEST['checkboxName']]) ? 0 ;
if the value is always 1, then use 1 instead of mysql_real_escape_string($_REQUEST[$_REQUEST['checkboxName']])
$data = array();
for($a=0; $a<max(array_keys($checkbox)); $a++) {
$data["chk$a"] = $checkbox[$a] ?: '0';
}
$sql = 'INSERT INTO accounts (\''.implode('\',\'', array_keys($data)).'\') VALUES ('.implode(',',$data).')';
Related
Lets say I have an array looking like this:
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30)
and a loop looking like this:
for($i=0;$i<count($sql);$i++){
$value[$i] = ($sql[$i]);
echo $value[$i];
}
I want the loop to iterate through the array and assign each value to a new variable.
In this code i tried to make it store the values in:
value1
value2
value3
But sadly this doesnt work, thus I am here seeking help.
Or is it a problem that i got an associative array instead of a numeric one?
I dont want to use this loop on this array only but on other arrays with different keys and length aswell.
Edit: I think I may have not wrote it cleary enough to tell you what i want to achieve:
I want to have three string values at the end of the loop not stored in an array:
Variable1 should contain "Peter"
Variable2 should contain "1"
Variable3 should contain "30"
Plus I want this loop to be dynamic, not only accepting this specific array but if I were to give it an array with 100 Values, I would want to have 100 different variables in which the values are stored.
Sorry for not being clear enough, I am still new at stackoverflow.
Going by your condition, assign each value to a new variable, I think what you want would be to use Variable variables. Here is an example:
<?php
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$count = 1;
foreach ($sql as $value) {
$x = 'value'.$count;
$$x = $value; //here's the usage of Variable variables
$count++;
}
echo $value1.'<br/>';
echo $value2.'<br/>';
echo $value3.'<br/>';
I went to your sample variables ($value1, $value2, etc.). I also changed your loop to foreach to easily loop the array. And I also added a $count that will serve as the number of the $value variable.
The $count wouldn't be necessary if your index are numeric, but since its an associative array, something like this is needed to differentiate the variables created
A brief explanation as requested:
$x contains the name of the variable you want to create (in this case, value1), then when you add another $ to $x (which becomes $$x), you are assigning value to the current value of $x (this equals to $value1='Peter')
To dynamically define a variable use $$. Demo
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$index = 1;
foreach($sql as $value){
${"value" . $index++} = $value;
}
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
In my PHP application. I am taking value from user and all these user values are stored in Array. And just for validation. I am comparing user input value with my array. :-
<?php
// Current Code
$masterArray = array(......); // ..... represents some 60-100 different values.
foreach($_POST as $key => $value) {
if(in_array($value, $masterArray)) {
$insertQuery = $mysqli->query("INSERTION stuff or Updating Stuff");
} else {
echo "Are you tampering html-form-data ?";
}
}
?>
But this is so worthless code, as it takes quite good time in updating or insertion.
Is there any better function that is way faster to check if value in slave array exists in master array ?
From Slave Array i Mean => List / Array of User Input value.
From Master Array i mean => List of my array value stored in page.
Thanks
I think i got the better option with array_diff.
Please let me know if i am doing anything wrong in below before i put this code in production page:- Thanks a lot for your efforts #J.David Smith & #grossvogel
<?php
$masterArray = array(.......); // My Master Array List
$result = array_diff($_POST['checkBox'], $masterArray);
if(count($result) > 0) {
// If they are trying to do some tampering , let them submit all again.
echo 'Something is not Right';
} else {
// If Person is genuine, no waiting just insert them all
$total = count($_POST['checkBox']);
$insertQuery = "INSERT into notes(user,quote) values ";
for($i=0;$i<=$total; $i++) {
array_push($values, "('someuser','".$mysqli->real_escape_string($_POST['checkBox'][$i])."')");
}
$finalQuery = $mysqli->query($insertQuery.implode(',', $values));
}
?>
Is my Code Better , I am testing it in localhost i don't see much of difference, I just want to know expert views if I am messing arround with something ? before i put this code in production page.
Update : This looks pretty better and faster than code in question.
Thanks
The only other way to do this is to use an associative array with your values as keys (well, you could custom-implement another storage container specifically for this, but that'd be overkill imo). Then, you can check with isset. For example:
$masterArray = array(....); // same thing, but with values as keys instead of values
foreach($_POST as $key => $value) {
if(isset($masterArray[$value])) {
// do stuff
} else {
// do stuff
}
}
I'm kind of curious what the point of doing this is anyway, especially given the statement printed by your echo call. There may be an even better way to accomplish your goal than this.
EDIT: Another method suggested by grossvogel: loop over $masterArray instead of $_POST. If you expect $_POST to be a large set of data consistently (ie most of the time people will select 50+ items), this could be faster. Hashing is already very fast, so you'll have to benchmark it on your code in order to make a decision.
$masterArray = array(...); // either style of definition will work; i'll use yours for simplicity
foreach($masterArray as $value) {
if(isset($_POST[$value])) {
// do stuff
}
}
foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'] = $door_check;
}
I have this little section of code that checks how many boxes were checked and then creates an array of the check box values.
The thing is, when I add that 'door' key, the array only adds one value no matter how many checkboxes were checked. When I just leave it empty, it adds all of them like [0], [1], [2] etc
Why is this?,
Your foreach() loops overwrites old variable each time. You need to make your session variable an array, for example
foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'][] = $door_check;
}
edit: Don't forget to validate that data when you save it for later use.
Try something like this:
foreach($_POST['door_check'] as $door_check) {
$_SESSION['front_door']['door'][] = $door_check;
}
or maybe even:
$_SESSION['front_door']['door'] = $_POST['door_check'];
I have the following function.
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
It requires that the variable $selected_screenshots is an array of values.
The problem is that I have to take the values from a mySQL look, that is reported below.
If there is only one value, everything works fine. But when there are more values in the DB, I cannot put all those values into the variable array.
In fact, since return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']); is outside the mySQL loop, it gets only the first value of the loop.
So how do I store all the values from the mySQL loop into the variable? And not only the first value?
I tried to manually assign the array to the variable in the loop $selected_screenshots = array($qryrow1['media_id']); but it does not work and I do not think it has any sense :)
$qry1="SELECT * FROM modzzz_articles_screenshots WHERE media_id='".$selected_screenshots_ID."' AND entry_id='".$this->aDataEntry['id']."'";
$qryr1=mysql_query($qry1) or die("Error selecting: ".mysql_error());
while($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots = array($qryrow1['media_id']);
} // END OF THE LOOK
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
Can anyone give me the solution, with code? I am really confused.
Thanks
Your code keeps overwriting $selected_screenshots with a new array each time. Instead, you want to append it:
$selected_screenshots = array();
while ($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots[] = $qryrow1['media_id'];
}
You can save all the mysql values by looping through your results and appending them to the end of $selected_screenshots to do this please look below. Right now you are just assigning $selected_screenshots one value and neglecting the other values, so $selected_screenshots is having the last value that mysql returns.
This is covered http://php.net/manual/en/language.types.array.php under the heading 'Creating/modifying with square bracket syntax'