Sort and separate names from a database - javascript

Could anybody point me in the right direction?
I have a database with a handful of messages. Each message has a username also..
I wish to use the names of the messages in a drop down menu so that the user can click a user and view the messages from the user.
THE PROBLEM: the drop down list shows every user of every message and i don-not know how to separate the users so that if there is 7 messages from ROB only 1 ROB will be shown in the drop down list..
I hope I am making sense here.
So if anyone could help me here, I would be grateful.
What sort of query should I be using the separate every user from the database so I can show them in the drop-down menu, as individual users...
Instead of the same user being shown for as many messages as the user wrote.
Below is the current query..
<div class='userbox'>
<header class='ubheader'>Contacts</header>
<section class='ubmain'>
";
$db = new PDO("mysql:host=localhost;dbname=messages", 'root', ''); // 1. set database with this instead of conect - or change conect to this
$query="SELECT * FROM `messagedatabase` WHERE `listID`='$listID' ORDER BY messagedate DESC";
$stat=$db->prepare($query);
$stat->execute();
$Mcount = $stat->rowCount();
$messagecount=$Mcount;
while($row = $stat->fetch()){
$messageaccountname=$row['messageaccountname'];
if ($messageaccountname != $useraccountname){
echo"<div class='ubnames' onclick='selectmessage(\"{$messageaccountname}\")'>{$messageaccountname}</div>";
}
}
echo "
</section>
</div>
";
Any help would be appreciated.
Many thanks.

The simple solution would be to add a DISTINCT clause to your query, such as:
SELECT DISTINCT messageaccountname FROM ....
Beyond that, it sounds like the database isn't normalized. Ideally, you'd have your accounts in a separate table that would be related to your messagedatabase table. But database design is a different discussion beyond the scope of this post.

Related

How can i create an animated Real Time Leaderboard Table?

I am trying to create a simple leader-board table that updates in real-time (or close enough) However I want it to be animated. I have been able to create an updating table that updates every second using a simple AJAX script that loads another PHP page. This all works fine and displays the table as it should, but I have no idea how to make it animate up/down if another play has a higher score than them.
What I have done:
leaderboard.html
<html>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#Refresh").load("leaderboardupdate.php");
var refreshId = setInterval(function() {
$("#Refresh").load('leaderboardupdate.php');
}, 1000);
$.ajaxSetup({ cache: false });
});
</script>
</html>
leaderboardupdate.php
<?php
$sql = "SELECT Name, Kills FROM Table ORDER BY Kills DESC LIMIT 5";
$result = $conn->query($sql);
echo '<div id="container">';
while($row = $result->fetch_assoc()) {
<div class="row">
<div class="name">'. $row["Name"] .'</div>
<div class="score">' .$row["Kills"]. '</div>
</div>';
}
echo '</div>';
?>
Like I said, this successfully creates a table and updates the data (In order of Kills from the SQL query) as it should, however I am wanting to make a row animate if they have overtaken another player in terms of Kills.
Closest thing I can find as an example:
https://codepen.io/bsngr/pen/WbLEvp
I have looked into Socket.IO, which although allows me to have real-time data, I don't think it will allow me to animate the row up/down, and that is the issue I face.
You are right sockets.io won't let you because it is not associated with animation in any way, however they will let you animate by letting your ap know "When to animate". Last time I checked sockets.io was meant for node.js not sure if they have support for PHP or if PHP has started supporting WebSockets.
WebSockets basically establish a connection between your client and server. They work on publish, subscribe model. So your server will open a connection and your client will subscribe to it. Once the connection between server and client is established your server will be able publish changes and client will be able to listen to them. Rough implementation will look something like this. First you will need to open a channel in your client so server and client can communicate through it.
<script>
var connection = sockets.open(`user-${userID}`) // will open a channel for some user
// once the connection is established you can listen to events
connection.on('update', function(data) {
//perfect place to animate stuff and update data
})
Then in your backend
<?php
$results = $conn->UpdateSomething(); // the place in your code where actions happen;
$socketConnection.trigger($channel, 'update', $results) // this will trigger update event on a $channel with data $results
?>
You can also use ServiceWorkers, LongPolling and ShortPolling to listen to real time changes and modify your DOM on events triggered by server
Steps To Animate
In order to the actual animation you can follow steps below
1 - Find the dom element containing the new leader, you can easily do it by getElementById and giving unique id to each item in board.
2 - Get the previous leader which will ideally be still on top of your leaderboard
3 - Once done, follow this example Swapping two HTML elements visually and on the DOM, and animate it all?. In this example clickedDiv is your new leader and prev is your old leader.
Animate.css is a useful Library I use for animations. Hope you find it useful.
Also, Try to use socket instead of ajax for real-time data.

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

How to control a combo box by using another combo box in HTML

I have 4 combo box in my HTML form. First 2 are Area and Subarea. Another 2 are Type and Subtype. I want to fill combo box using database values. I already filled first combo box i.e. Area ID but after that when I select particular Area then according to that value I want to fill SubArea combo box. I can't do it in PHP only. And I am new to JavaScript and Ajax. Will you please help me??
Many people have in fact tackled this problem before. It is frequently refered to as a "dependent" or "related" or "cascading" selectbox/combobox. Here's a google search to get you some plugins for javascript (using the excellent jQuery library): https://www.google.com/search?hl=en&q=jquery+dependent+select&oq=jquery+dependent+select
Also, the "related questions" on the right side of this question look fairly pertinent to your situation, try reading up on some of them.
Please note that the FAQ encourages questions to match one or all of the criteria
a specific programming problem
a software algorithm software tools
commonly used by programmers practical, answerable problems that are
unique to the programming profession
Which, as mustafa.0x points out, your question is overly broad and does not include a specific question. Take a swing at using a plugin, or research some non-jQuery solutions, and if you run into trouble, post another question with the specific problem you're running into.
I use an event in javascript then I can retrieve the id being use from it but sadly cannot import it to php.
`
* Department Name
<select name = "dept_type" id = 'new_jobdep_id' onchange = 'clickSelect(this.value)' class= "form-control" required>
<option value = "" selected>-----Select Department---</option>
<?php
$sql_in = mysql_query('Select * from department where DeptStatus = 1');
while ($r = mysql_fetch_assoc($sql_in)){
$depID = $r['DeptID'];
$depName = $r['DeptName'];
$depName = ucwords($depName);
?>
<option value = <?php echo $depID; ?> required><?php echo $depName; ?> </option>
<?php
}
?>
</select>`
hopefully this code can give you a good logic.
Pls.. answer this question..
I just want to get the value the select statement below then make it as a reference to another combo box by inserting the retrieve ID from php to my query..
This is a broad design question, but you'll need to attach an event to the combo box, so when an item is selected, you execute an AJAX request which retrieves the sub-items of the selected item.

How to create a textbox that display message when mouseover?

I have a sql query that obtain a string called description from the database
Also , i have a table that contain a mail list
I would like for each mail list name, when the mouse over it, it display a text block that contain the description
Are there any plugin , or how to do that? Thank you.
I use a jQuery plug-in called TipTip, which is very simple to implement.
The PHP(for the query). You can use whatever, this is an example.
<?php
$q = 'your sql query'
$query = mysql_query($query)
while($row = mysql_fetch_array($query)){
?>
<div class="email-list-name-<?=$row['id']?>"> <?=$row['email-list-name']?> </div>
<div class='description-for-email' style='display:none;'><?=$row['description']?></div>
<?php } ?>
The jQuery:
$(function(){
$('div[id^="email-list-name"]').click(function(){
$('.description-for-email').hide(); //hide all message displays
$(this).next('.description-for-email').show(); //show the next description for our email we clicked
});
});
You didn't really provide any other information, so I just threw together a general example.
You can use the title attribute of html for that or make use of tooltip . You can easily find an example of tooltip. But if you trying to fetch the data from your db on the run time..i would say thats a bad idea

cakephp - Javascript

We are working on an application using the CakePHP framework
Basically, its a questionnaire application and it has a few dependant questions, i.e. based on a response to a specific question, it needs to show or hide the next one
For e.g.
Question: Are you married? Yes/No
If the user selects Yes, then using javascript the next question gets displayed for user input
Question: Spouse's name
Saving this information is fine, but when editing, when populating the form, we would want to be able to display the fields for which user has inputted data - in this case, it needs to show the field that has the spouse's name
Since by default we are hiding the spouse name field, when editing, it doesn’t display the field, even though there is a value to it
Is there some way that CakePHP can handle this or does it require us to write some javascript to take care of this?
Thanks in advance.
CakePHP does not manage this for you. While CakePHP is very powerful and a great framework, it will not write this kind of logic for you. You must write it.
I would suggest making the EDIT screen different from the ADD screen. Build the list of values from the database and display the fields that have values (and include any empty fields that should require values).
Keep in mind reusable does not necessarily mean that all CRUD actions fit into the same view.
Like others I advise you use differents EDIT and ADD screens.
But you can try make it with Javascript like this:
<script>
function enableDisableField(targetFieldId){
var targetField = document.getElementById(targetFieldId);
var checkbox = event.target;
console.log(checkbox.checked);
if (checkbox.checked){
targetField.disabled = false;
targetField.value = "empyt";
}else{
targetField.disabled = true;
targetField.value = "empyt";
}
}
</script>
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, 'disabled']); ?>
It works well for ADD, but if you and EDIT you have to change de disable value according a field value:
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, !isset($user->married) ? 'disabled' : '' ]); ?>

Categories

Resources