I want to check if my array contains a duplicate value. I have a form where i pass a Chapter ID with the following method:
<input name="chapter_id[]" type="number" value="<?= $row_chapter_list['chapter_id'] ?>">
To update my database i pick this input and do the update w/o any issues:
if (isset($_POST['chapter_id'])) {
// Update Kapitelnummer
$statement = $pdo->prepare("UPDATE questionaire_chapter SET chapter_id = :chapter_id WHERE id = :id");
$statement->bindParam(":chapter_id", $chapter_id, PDO::PARAM_STR);
$statement->bindParam(":id", $id, PDO::PARAM_INT);
foreach ($_POST['chapter_id'] as $index => $chapter_id) {
$id = $_POST['chapter_inc_id'][$index];
$statement->execute();
}
}
A typical var_dump result looks like:
array(3) { [0]=> string(1) "1" [1]=> string(2) "12" [2]=> string(2) "12" }
In this array example the value "12" is present in two strings. I would like to create a mechanic to count double values and and use the result in a PHP if/else. i want to avoid that the a duplicate chapter ID gets written into my database.
My first try to count the string is this:
print_r(array_count_values($_POST['chapter_id']));
Which gives me a result like this
Array ( [1] => 1 [12] => 2 )
Now i am missing the method to implement a if else to check if the result is not 1.
Any idea how to do this?
You can use array_unique() to get an array where any duplicates has been filtered out. Using that, you can compare it to the original array:
if ($array != array_unique($array)) {
echo "The arrays are not the same, which means that there are duplicates";
}
Related
I am working on a quiz app, so the users have MCQ's and on submitting the quiz I need to show the result.
Here is the answers table in the mysql db. Similarly, There is questions table which has the id and question columns, containing the question id and question respectively.
So I am querying the db from the model like this, this returns me an associative array:
$testQuery = $this->db->query("SELECT quiz_id, correct_option FROM answers");
if ($testQuery->num_rows() > 0) {
return $testQuery->result_array();
}
Here, I'm printing the array in my controller, Which looks like this on doing the foreach:
$allCorrectOptions = $this->DataModel->readCorrectOptions();
$asize = sizeof($allCorrectOptions);
for($i = 0; $i < $asize; $i++){
echo "<pre>";
var_dump($allCorrectOptions[$i]);
echo "</pre>";
}
The Result of the above snippet:
array(2) {
["quiz_id"]=>
string(2) "13"
["correct_option"]=>
string(13) "Maruti suzuki"
}
array(2) {
["quiz_id"]=>
string(2) "14"
["correct_option"]=>
string(6) "Kotlin"
}
array(2) {
["quiz_id"]=>
string(2) "15"
["correct_option"]=>
string(4) "BOSS"
}
In the view there are radio input tags and the name attribute contains an array (allques) with quiz_id as key so when the user submits the test, I'm doing this to get the quiz_ids and selected values.
$nums = $this->input->post('allques');
foreach ($nums as $key => $value) {
echo "<br>" . $key . "==" . $value;
}
The Result of the above snippet:
13==Maruti suzuki
14==MongoDB
15==Ubuntu Linux
So what I am thinking of doing is, getting the array result of the db query similar to the the snippet result above, so that I can compare the quiz_id and correct_option's with the user submitted values with the help of a loop like: if quiz_id.this == submitted quiz_id && correct_option.this == submitted value then correct_answers++. After that showing the result
If this approach of checking is not effective, then is there any other way to do this properly.
I have figured it out, it can be done like this.
foreach ($allCorrectOptions as $key) {
echo $key['quiz_id'] . "==" . $key['correct_option'] . "<br>";
}
I am trying to provide a count of certain sizes of lockers. My SQL statement is:
$sql = "SELECT Concat(`Height`, 'x', `Width`, 'x', `Depth`) as Locker, count(*) from lockers GROUP BY `Height`, `Width`, `Depth` ";
a var_dump in a loop of the rows gives me the following (many more rows are possible):
array(2) { ["Locker"]=> string(8) "15x30x45" ["count(*)"]=> int(6) }
array(2) { ["Locker"]=> string(8) "45x30x45" ["count(*)"]=> int(4) }
I want to obtain a JSON string that looks like this:
{
"SizeList": {
"15x30x45": 6
"45x30x45": 4
}
}
I have tried a lot of different methods (including converting it into an object, but I can't get the value of the size as an index. For example, I get different variations of:
[0]=> string(31) "{"Locker":"15x30x45","count(*)":6}"
[1]=> string(31) "{"Locker":"45x30x45","count(*)":4}"
Any help appreciated...
You could just manually create the object like this:
$sizeList = new stdClass();
foreach ($results as $row) {
$sizeList->{$row['Locker']} = $row['count(*)'];
}
echo json_encode(array('SizeList' => $sizeList));
Here i have a query to my MySql database and I am taking out all the information about a course to be put in a row and displayed in my table. The last column of the table is a check box, that check box I want to make it so it will save the row of data for each row that it is checked off. The variable i chosen was courses[], to be saved in array then saved in session to be accessed else where. I'm not sure how to extract the row data to put in to my array. Right now I have value='$row2013 and that doesnt work because when I var_dump($courses) = array(5) { [0]=> string(5) "Array" [1]=> string(5) "Array" [2]=> string(5) "Array" [3]=> string(5) "Array" [4]=> string(5) "Array" } , Which I have selected five courses.
To sum things up, I am not saving the right thing.
case 2013:
$string2013 = "SELECT Course.CourseCode, Course.Title, Course.WeeklyHours, Semester.Term, Semester.SemesterCode
FROM Course, CourseOffer, Semester WHERE Semester.YearNum='$selectedYear' AND Course.CourseCode=CourseOffer.CourseCode AND
Semester.SemesterCode=CourseOffer.SemesterCode";
if($Result2013 = mysqli_query($link, $string2013))
{
echo "<form action='CourseSelection.php' method='get'>
<table><tr><th>Code</th><th>Course Title</th><th>Hours</th><th>Term</th><th>Select</th></tr>";
while($row2013 = mysqli_fetch_assoc($Result2013))
{
echo "<tr><td>$row2013[CourseCode]</td><td>$row2013[Title]</td><td>$row2013[WeeklyHours]</td>
<td>$row2013[Term]</td><td><input type='checkbox' name='courses[]' value='$row2013'></td></tr>";
}
echo "</table>";
}
else
{
echo "<p>" + mysqli_error($link) + "</p>";
}
break;
value='$row2013' ??? should be for example value='$row2013["CourseCode"]'
You should try to save only the row ID in the value of checkbox. This way you can easily recall a row from the database by its ID. $row2013["CourseCode"] should work.
When you do the POST request, you will get an array of IDs ($_POST['courses']). Of course you need to treat it as array, so you must iterate over it in order to get all the rows you selected.
If you var_dump($_POST['courses']) you should see something like this, assuming you have selected the first 5 rows:
array (size=5)
0 => string '1' (length=1)
1 => string '2' (length=2)
2 => string '3' (length=3)
3 => string '4' (length=4)
4 => string '5' (length=5)
Now just query the database according to the selected rows, and you're good to go:
SELECT *
FROM Course
WHERE CourseCode = 1
OR CourseCode = 2
OR CourseCode = 3
OR CourseCode = 4
OR CourseCode = 5
You could do it with jQuery, which you could use to handle and validate your form also. Or, with each row, you could build an array for that row and pass it as a hidden value. Then when it posts, see that if the checkbox is checked, and if it is, have the script use the hidden value.
Way 1:
If I can assume that your Course table has one primary key column ('CourseCode') then you don't have to save the entire row as the value in a checkbox. You only need to save the CourseCodes for the checked rows. Then, you can add unique hidden inputs for each of the other table cells by appending the CourseCode to the input name, for example:
<input type='hidden' name='Title_" . $row['CourseCode'] . "' value='" . $row['Title'] . "'> etc.
In other words $_GET["courses"] will contain an array of CourseCodes which represents the rows which were clicked. Then you can iterate over $_GET["courses"] and read the names of the other variables easily:
$lst_course_codes = !empty($_GET["courses"]) ? $_GET["courses"] : array();
foreach ($lst_course_codes as $code) {
$title = $_GET["Title_$code"];
etc...
}
Way 2: Store the checkbox values as json encoded strings: json_encode($row2013)
Then you can just iterate again (in CourseSelection.php):
foreach ($_GET["courses"] as $json) {
$arr_row = json_decode($json, true);
$title = $arr_row["Title"];
etc...
}
I haven't checked closely for errors, but you get the idea.
I am looking for the most efficient method to do the following...
I have a table with three fields: id, eventid and movetype - and I have the following code to query the database for all entries with a matching eventid :
$get_results = mysql_query("SELECT * FROM table WHERE eventid='$eventid'");
while($row = mysql_fetch_array($get_results)){
// store results in array
$move_type_array = explode(" ", $row['movetype']);
}
Please note: movetype can only be three values: Internal, Outgoing, Incoming
Using a set of dummy data, var_dump($move_type_array) could output:
array(1) { [0]=> string(8) "Internal" } array(1) { [0]=> string(8) "Internal" }
Another example of an output would be:
array(1) { [0]=> string(8) "Internal" } array(1) { [0]=> string(8) "Incoming" } array(1) { [0]=> string(8) "Outgoing" }
I then need to check the output to see if the following conditions are met:
Does the array contain Internal twice?
If the array only contains Internal once, then does the array also contain Incoming and Outgoing?
If either of the conditions are met then a message should be displayed telling them which condition has been met, otherwise a message should tell them that the conditions have not been met.
I have tried using a number of PHP functions such as in_array(), and also tried storing the data in a string and using preg_match() however I was unsuccessful in both methods.
Try this:
$result = mysql_query("
SELECT SUM(IF(movetype = 'Internal', 1, 0)) AS internal,
SUM(IF(movetype = 'Outgoing', 1, 0)) AS outgoing,
SUM(IF(movetype = 'Incoming', 1, 0)) AS incoming
FROM table
WHERE eventid = $eventid
GROUP BY eventid
");
$count = mysql_fetch_array($result);
if ($count['internal'] >= 2 || ($count['internal'] == 1
&& $count['outgoing'] >= 1
&& $count['incoming'] >= 1)) {
echo 'Yes';
} else {
echo 'No';
}
// 1. Don't use '*' - fetch only required fields!
// 2. Don't use mysql_* functions - they are obsolete! Use PDO or MySQLi instead.
$get_results = mysql_query("SELECT `movetype` FROM table WHERE eventid='$eventid'");
while($row = mysql_fetch_array($get_results)){
// Count the values
$arr = array_count_values(explode(" ", $row['movetype']));
// Check them here
if(isset($arr['Internal'])) {
if($arr['Internal'] === 2)
echo ' Internal: 2'.PHP_EOL;
else if($arr['Internal'] === 1
&& isset($arr['Incoming'])
&& isset($arr['Outgoing']))
echo ' Internal: 1, Incoming and Outgoing'.PHP_EOL;
}
}
I have a multidimensional array called $data that is basically data extracted from a table into the array.
This is how I get my array using JS_extractor:
set_include_path(get_include_path() . PATH_SEPARATOR . './library/');
require_once 'JS/Extractor.php';
$extractor = new JS_Extractor(file_get_contents('temp.html'));
$body = $extractor->query("body")->item(0);
$table = $body->query("//table[#class='rstatisztika_tabla']")->item(0);
$data = array();
foreach ($table->query('tr') as $i => $tr) {
if ($i == 0) {
continue;
}
$a = $tr->query('.//a');
$a = $a->item($a->length - 1);
$url = $a->getAttribute('href');
$parsed = parse_url($url);
parse_str($parsed['query'], $query);
$data[] = array(
$a->textContent,
$url,
$query['user'],
);
}
//var_dump($data);
when I actually do
var_dump($data);
I get this:
array(3)
{
[0]=> array(3)
{
[0]=> string(4) "Thad"
[1]=> string(7) "http://localhost/index.php?m=karakterlap&user=91"
[2]=> string(2) "91"
}
[1]=> array(3)
{
[0]=> string(4) "Bill"
[1]=> string(8) "http://localhost/index.php?m=karakterlap&user=110"
[2]=> string(3) "110"
}
[2]=> array(3)
{
[0]=> string(7) "Thadson"
[1]=> string(7) "http://localhost/index.php?m=karakterlap&user=147"
[2]=> string(3) "147"
}
}
I also have a Mysql database table called warlord
CREATE TABLE IF NOT EXISTS `warlord` (
`id` int(5) NOT NULL default '0',
`name` varchar(35) character set utf8 NOT NULL default '',
`active` tinyint(1) NOT NULL default '1',
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `warlord` (`id`, `name`, `active`) VALUES
(2, 'Admin', 0), (100, 'Thadson', 1), (147, 'John', 1);
From the array, I want to add the new users (Thad & Bill) to the warlord table and set them active (1)
I want the user (Thadson), who is also in the array, to stay active (1)
However I want the user (John) who is not in the array, set to inactive (0)
and leave admin who is also not in the array (and is already inactive) inactive (0)
I know this is a very beginners question, but how do I do this?
Thanks
You might want to use array_map function to set a callback function for the multi-array and process it accordingly:
array_map
I saw this and I have tried it:
$data = array();
for($i=0; $i<count($data_array); $i++){
$data_items[$i] = explode(',', $data_array[$i]); // create a multi-dimensional array
$data[] = '( ' .$data_items[$i][2]. ', '.$data_items[$i][0]. ', '. 1 .')';
}
$sql = "INSERT INTO warlord(id, name, active) VALUES ('".$data_items[$i][2]."','".$data_items[$i][0]."','1') ";
...to get the data into my table
I ignore the 2nd elements from the array (The ones that look like this: [1]=> string(7) "user=91") and I try to insert elements [2] and [0] into the table and make the new users active with placing 1 into the active field.
This obviously doesn't do all I need (actually it doesn't do any of it) and I have no idea what I'm doing. This is why I'm asking for help.
If I was to approach this question I would firstly try to organise my arrays (the $data array and also the array from the database) into a similar format (possibly using the id as the array key) so that I could use array_intersect to work out the people in both $data and $database (ie. people who should set active) and array_diff to work out the people in $data and not in $database (ie. the people who need to be added to the database) and then array_diff again (with $database first this time) to work out the people in $database and not in $data (ie. the people who should be set inactive).
Hope this helps put you on the write track. Sorry but I don't have the time to actually write the code for you.