Finding a match between array and database - php

I have an array called "selected_checkboxes". In my database I have multiple columns and some of them contain the value 1, otherwise the value will be NULL. The names of those columns are exactly the same as the values of the array.
I would now like to check dynamically if the values of my array ($_POST['selected_checkboxes']) match with the values of my columns in the database. If ALL values from the array have the value 1 in the database, it should echo something like Match!
This is what I have tried so far but I think it's completely wrong:
if(!$result = $db->query("SELECT * FROM products")){
die('Error');
}
while($row = $result->fetch_object()){
foreach($_POST['selected_checkboxes'] as $value) {
if ($value == 1) {
$say .= $value . ' is = 1';
}
}
}
echo $say;
I appreciate any help!!
Edit:
This is how the array 'selected_checkboxes' is getting generated:
$('.show_result').click(function() {
// Get all selected checkboxes
var selected = [];
$.each($("input[type=checkbox]:checked"), function(){
selected.push($(this).attr('id'));
});
// Get the selected option field
selected.push($('#PG_Select_Bereich1').val());
// Deliver data to PHP
$.ajax({
url : "typo3conf/ext/produkteguide_sg/pi1/products.php",
type: "POST",
data : { selected_checkboxes:selected },
success: function(data, textStatus, jqXHR)
{
$("#PG_Resultate").html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
//alert(errorThrown);
}
});
And this is how my database looks like:

I've done something similar but in a different way, I hope this is what you're looking for:
// Query execution
$result = mysqli_query($CONN,"SELECT * FROM whatever");
while($row_from_db = mysqli_fetch_array($result)){
$db_value = is_null($row_from_db['myValue']) ? 0 : 1;
$check_value = !isset($_POST['selected_checkboxes']['myValue']) ? 0 : 1
echo $db_value == $check_value ? "Match!" : "Not matching :(";
}

I am writing pseudo code for your requirement.
1) loop through array.
2) while loop through array if value of element is found 1 the go to next step otherwise continue loop.
3) If array element value is 1 then get a key of element and prepare sql query which checks that column name same as key name have value as 1 for each record then mark it as Match.
Hope this helps to you. If you not get with this then let me know i will write the code for you.
Edit:
Each of your checkbox name must be same as column name in database.
$array_checkbox = $_POST['selected_checkboxes'];
$query =" SELECT count(*) FROM <tabel_name> WHERE 1=1";
// get count from query and store it in $total_rows variable
$total_rows = 10; // for example purpose we take count value as 10
foreach($array_checkbox as $key => $checkbox){
$query = $query =" SELECT count(*) FROM <tabel_name> WHERE $key=1"; // here we take key of array as column name in sql query and getting that how many rows of the column have value 1
// get count from query and store it in $result variable
$result = 10;
if($result == $total_rows){
echo "Match";
}
}
Hope this is according to your requirement.

Related

How to bring more than one row (mysql) result inside the same variable when running a json_encode?

I am running a POST + json code to collect data from database, all results come with only one value (this is correct), however there is only one column which should show more than one value but shows only the first one. What I need to change in my code to get this list instead of the first row result?
I've run one MYSQL query linking three databases those share the same id PCRNo, the first two databases tPCR and tcomplement should only have one result and the third one should receive more results due to we can have more lines with the same id.
This is my JavaScript
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
$('#description').val(data.Name);
$('#Comments').val(data.Comments);
$('#originator').val(data.Creator);
$('#change_type').val(data.Category);
$('#product_type').val(data.Product);
$('#req_dept').val(data.Department);
$('#flow').val(data.Flow_Start_Date);
$('#own').val(data.Owning_Site);
$('#impacted').val(data.Impacted_Site);
$('#approval').val(data.Meeting_Status);
$('#review').val(data.Review_Date);
$('#cat').val(data.Cat);
$('#cost').val(data.Cost);
$('#labor').val(data.Labour);
$('#volume').val(data.Volume);
$('#request').val(data.Request);
$('#justification').val(data.Justification);
$('#PCNlist').val(data.PCNNo);
$('#monitor').val(data.Monitor);
$('#env').val(data.Environment);
$('#trial').val(data.Trial);
$('#resp').val(data.Responsible);
$('#deadline').val(data.Deadline);
$('#dataModal').modal('show');
}
});
});
$(document).on('click', '#update', function(){
var pcr_number = document.getElementById("PCR").value;
var Comments= document.getElementById("Comments").value;
var approval= document.getElementById("approval").value;
var review= document.getElementById("review").value;
var cat= document.getElementById("cat").value;
var monitor= document.getElementById("monitor").value;
var env= document.getElementById("env").value;
var trial= document.getElementById("trial").value;
var resp= document.getElementById("resp").value;
var deadline= document.getElementById("deadline").value;
var PCC = document.getElementById("PCC").value;
$.ajax({
url:"edit.php",
method:"POST",
data:{pcr_number:pcr_number, Comments:Comments, PCC:PCC, approval:approval, review:review, cat:cat, monitor:monitor, env:env, trial:trial, resp:resp, deadline:deadline},
dataType:"text",
success:function(data)
{
alert('PCR Information Updated');
}
});
});
});
</script>
this is my fetch.php
<?php
$SelectedPCRNo = $_POST['pcr_number'];
if(isset($_POST['pcr_number']))
{
$output = '';
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$dbConnected = #mysqli_connect($hostname, $username, $password);
$dbSelected = #mysqli_select_db($databaseName,$dbConnected);
$dbSuccess = true;
if ($dbConnected) {
if ($dbSelected) {
echo "DB connection FAILED<br /><br />";
$dbSuccess = false;
}
} else {
echo "MySQL connection FAILED<br /><br />";
$dbSuccess = false;
}
$sql = mysqli_query($dbConnected, "SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo INNER JOIN change_management.tPCN ON change_management.tPCR.PCRNo = change_management.tPCN.PCRNo WHERE tPCR.PCRNo = '".$_POST['pcr_number']."'");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
}
?>
I have no problems with the results and the table is filled OK, only the #PCNlist should be filled with the values of all rows it is related and now just is just coming one value, the first row only. Is there any way to bring the whole PCNlist only changing some code at the fetch.php?
If I understood you correctly, the table tPCN can contain multiple rows associated with each PCR number. And you want to fetch all these rows and return them in your JSON.
If you want to achieve that, but also make sure the other two tables only return one row, then I think simply you should remove the JOIN to tPCN in your first query, and then create a second query to fetch the tPCN rows specifically.
$output = [];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo WHERE tPCR.PCRNo = ?");
$stmt->bind_param('s', $_POST['pcr_number']);
$stmt->execute();
$result = $stmt->get_result();
//select a single row from the result and assign it as the output variable
if ($row = $result->fetch_assoc()) {
$output = $row;
}
$stmt2 = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt2->bind_param('s', $_POST['pcr_number']);
$stmt2->execute();
$result2 = $stmt2->get_result();
$output["tPCN"] = array(); //create a new property to put the tPCN rows in
//loop through all the tPCN rows and append them to the output
while ($row2 = $result2->fetch_assoc()) {
$output["tPCN"][] = $row2;
}
echo json_encode($output);
This will produce some JSON with this kind of structure:
{
"PCRNo": "ABC",
"CreationDate": "2019-08-07",
"Name": "A N Other",
//...and all your other properties, until the new one:
"tPCN": [
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": "SomeOtherValue",
},
{
"SomeProperty": "SomeSecondValue",
"SomeOtherProperty": "SomeOtherSecondValue",
}
]
}
You will then need to amend your JavaScript code to be able to deal with the new structure. Since I don't know exactly which fields come from the tPCN table, I can't give you an example for that, but hopefully it's clear that you will need to loop through the array and output the same HTML for each entry you find.
N.B. As you can see I re-wrote the query code to use prepared statements and parameterised queries, so you can see how to write your code in a secure way in future.
P.S. You have a lot of code there in the "success" function just to set the values of individual fields. You might want to consider using a simple JS templating engine to make this less verbose and cumbersome, and generate the HTML you need with the values automatically added into it in the right place. But that's a separate issue, just for the maintainability of your code
I've added this code into my ajax function to bring only what I needed and it works + what #ADyson has posted.
var PCN = data.tPCN;
var i;
var PCNList = '';
for (i = 0; i < PCN.length; i++){
var PCNList = PCNList + PCN[i]['PCNNo'] + ' - ' + PCN[i]['Stage'];
}
$('#PCNlist').val(PCNList);

get a particular column element of the next table row from database

I have a query which selects userid,messageid,statusid from tableA like following.
$qry = mssql_query('select userid,messageid,statusid from tableA');
if(mssql_num_rows($qry))
{
$data = mssql_fetch_array($qry)
{
//if(current_status_id column value != next_status_id column value)
$status = $data['statusid'];
}
}
I need to compare the value of current statusid column with the immediate next row statusid column like this if(current_status_id column value != next_status_id column value).Is this possible.Pls help me
$qry = mssql_query('select userid,messageid,statusid from tableA order by statusid');
while (($row=mssql_fetch_array($qry) !== FALSE) {
if (isset($previous) && $previous['statusid'] !== $row['statusid']) {
// do what you gotta do here
}
$previous = $row;
}
I added order by statusid to your SQL so that you do get an order set of data. And rather than trying to "look ahead" to the next row, the code above "looks back" to the previous row ... which is effectively the same. You've got the data of the two rows in $previous and $row so you should be able to do what you wanna do with $previous.
I have created an array and assigned the results into it.Then I used while loop and checked if the current element is not equal to next element.
$i=1;
while (($row = mssql_fetch_array($qry, MYSQL_ASSOC)) !== false)
{
$data_array[] = $row; // add the row in to the results (data) array
}
mssql_data_seek( $qry, 0 );
while($msgDetailChilds = mssql_fetch_array($qry)){
if($data_array[$i]['groupid']!=$data_array[$i-1]['groupid'])
{
//do stuff
}
}

How is infinite scrolling made?

How struggling to make a PHP call to get items to load on scroll. I have a while loop of items and need a php code for infinity.php to load more items to the ID "stream" but can't figure out a solution. Would be greatful for some expertise help!
PHP on Main-page:
<?php
$getStream = mysql_query("SELECT * FROM ".$DBprefix."xxx WHERE xxx='xxx' AND status='1' ORDER by id");
$counter = 0;
$max = 2;
while($stream = mysql_fetch_array($getStream) and ($counter < $max)) {
$counter++;
}
?>
I have this Jquery:
function lastAddedLiveFunc()
{
$('div#loader').fadeIn();
$.get("infinity.php", function(data){
if (data != "") {
//console.log('add data..');
$("#stream").append(data);
}
$('div#loader').empty();
});
};
HTML:
<div id='stream'></div>
I think you're missing a few key pieces here. Firstly, when we use infinte scroll and we're fetching data from the database, you need a LIMIT clause, the LIMIT clause allows for a offset, total relationship. where offset indicates the row to start at, and total is how many rows we want to take.
Initially, you'll have something like this
$offset = $_GET['offset'] ? $_GET['offset'] : 0; //start at 0th row if no variable set
$total = $_GET['total'] ? $_GET['total'] : 20; // get 20 rows if no variable set
In the above, we're using ternary variable assignment to check if an argument is being passed to us, if not, then we use the default value. We're going to use mysqli and the prepared, bind_param, execute, bind_result and fetch_assoc() methods.
if( $getStream = $mysqli->prepare("SELECT * FROM ? WHERE xxx=? AND status=? ORDER by id LIMIT ?,?"):
$ret = ''; // a variable place holder
// in the above statement, fill in the ?'s
// the actual ? will be the value we wish to return, in order from first to last.
$getStream->bind_param('ssddd', $DBprefix.'xxx', 'xxx', 1, $offset, $total);
//execute our query
$getStream->execute();
$getStream->bind_result($field1, $field2, $field3, $field4); // each field needs it's own variable name, that way we can access them later.
while($row = $getStream->fetch_assoc()):
$ret .= '<div class="my-infinite-element"><h3>'. $field1 .'</h3><p>'. $field2.'</p>'. $field3 .', '. $field4 .'</div>';
endwhile;
echo $ret;
else:
return FALSE;
endif;
Now that's how we'll handle getting our data back using MySQLI; now let's make the ajax statement to get the data back.
$.ajax({
type: 'GET',
url : 'infinity.php',
data: {
'offset' : $('.my-infinite-elements').length,
'total' : 20
},
success: function(data){
if(false !== data){
$('#stream').append(data);
}
}
});
In the above, the only thing we should be worried about is $('.my-infinite-elements').length. We used a class of my-infinite-elements for each element we returned. This way, we can count the existing length of elements on the page, which will provide our offset value (or where we want to start getting the rows from). If we pulled out 20 results from our DB, it's 0 based, so we'll get 0-19. When we do .length, we're going to get a 1 based result, which will return 20, instead of 19. That's okay, because we DON'T want the very last row returned also, so our logic is fine. The two variables offset/total in our ajax function, correspond to our ternary variable assignment.

How to return latest Mysql entry through JQuery/Ajax request

I am trying to pull the latest entry of a mysql table through ajax and display it as html content inside a div. I have ajax and php functioning correctly, the only problem I have is that I want to query for new entries and stack the results at a time interval within a loop and I've run into two problems: getting the data to behave like a normal javascript string, and getting the loop to only return unique entries.
update.php file
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax request loop:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
The problem is by doing SELECT * FROM conversations you keep requesting whole table -- although you only take the last one.
Your code need to remember which comment has been loaded, and only get any comment newer than that.
For example, assuming your primary key is incremental, do SELECT * FROM conversations WHERE convid > ?. Replace ? with latest comment that has been loaded. If you're loading for the first time, just do SELECT * FROM conversations
You could pass the last comment id displayed using request parameter into update.php. Also I recomment returning the data in JSON format so you can return a collection of comment and id and parse it easily
This will count the comments in the table and select the last entered comment then pass them to ajax as json data only if the received count is lower than the count of the comments in the table:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10
insert_date the date time comment is inserted, i hope you will have a field for storing that if not add it now

it is not inserting correct values in db?

I want to insert a sessionid and a set of students into the db.
The sessionid can be found in line of code below:
<td><input type='hidden' id='currentId' name='Idcurrent' readonly='readonly' value='4' /> </td>
A set of students are displayed in a select box as so:
<select id="studentadd" name="addtextarea">
<option value='1'>u08743 - Joe Cann</option>
<option value='4'>u03043 - Jill Sanderson</option>
<option value='7'>u08343 - Craig Moon</option>
</select>
Now I am using ajax to get both the sessionId value and the student's value and post them into a seperate php page where the insert happens by using code below:
function submitform() {
$.ajax({
type: "POST",
url: "updatestudentsession.php",
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
dataType:'json', //get response as json
success: function(result){
if(result.errorflag){
$("#targetdiv").html('success');
}else{
//you got success message
$("#targetdiv").html('error');
$('#targetdiv').show();
}
}
});
}
Below is the seperate php file updatestudentsession.php where it is suppose to do the insert:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Now the problem I am having is that is not inserting the correct data in at all. It is insert the value 0 in both the SessionId and StudentId fields. Below is what the table should look like after the insert:
SessionId StudentId
4 1
4 4
4 7
Instead it looks like below:
SessionId StudentId
0 0
My question is what is causing it to not be able to retrieve and insert the correct data into the db?
Suppose part of problem is here:
Idcurrent: $('#currentid').val(),
In your HTML code ID is currentId when you are trying to get an element with id currentid. id selector is case sensitive. So, you simply pass nothing to your PHP as jquery can't find an element.
Not sure what is wrong with $studentid, but I see no reason to use an array there as you always pass only one value, so try to change your php code like below:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
//var_dump($studentid);
//var_dump($sessionid);
//var_dump($_POST); - this is additionally to see whole $_POST variable.
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Also, see at commented out var_dump lines at the beginning. They will print values of your variables so you will be able to see what is actually set there. (as it is ajax, you will need to open developer tools and see what is returned in result on network tab)
UPD:
According to the latest comment, appears that$_POST['addtextarea'] is an array. Because of that code is modified to handle that. Please note how that value is taken:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
Old code, which is:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
results in two level array. So $studentid is an array which contains one element which is an array also. That is why old for each loop is not working. $id were an array. And it was converted to 0
I think there is a probel in data :
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
Try :
data: {
"Idcurrent": $('#currentid').val(),
"addtextarea":$('#studentadd').val()
},
Please not the double quotes "Idcurrent"

Categories