<?php>
if (isset($_POST['search']))
{
$startDate = $_POST['start'];
$startDate = str_replace('/', '-', $startDate );
$startDate = date("Y-m-d", strtotime($startDate));
echo $startDate;
$endDate = $_POST['end'];
$endDate = str_replace('/', '-', $endDate );
$endDate = date("Y-m-d", strtotime($endDate));
echo $endDate;
$model = $_POST['model'];
echo $model;
$dates = getDatesStartToLast($startDate, $endDate);
for ($i=0; $i < count($dates); $i++){
echo "<tr>";
echo "<td><text class = 'dateselect'>$dates[$i]</text></td>";
$query = mysqli_query($conn, "SELECT * from electec_db where DateInputTime >= '$dates[$i]' and DateInputTime <= '$dates[$i] 23:59:59' and Model = '$model'");
$count = mysqli_num_rows($query);
// echo $count;
echo "<td>$count</td>";
$arrays = array("Result = 'NG'", "Species = 'Burr'", "Species = 'Dirt'", "Species = 'Scratch'", "Species = 'Cracked'", "Species = 'Gas'" );
for ($j=0; $j < count($arrays); $j ++){
$query = mysqli_query($conn, "SELECT * from electec_db where DateInputTime >= '$dates[$i]' and DateInputTime <= '$dates[$i] 23:59:59' and Model = '$model' and $arrays[$j]");
$count = mysqli_num_rows($query);
echo "<td>$count</td>";
// And this is jsp code
<script>
$('.dateselect').click(function() {
var dateSelect = $(this).text();
alert(dataSelect)
}
</script>
This is php code and javascript code.
When I click echo "$dates[$i]"; part,
I want to make react in script like alert dateSelect variable. But it doesn't make any reaction.
How to make a table react in javascript when clicked in php?
Do you have jQuery installed in your project? That's what the $ indicates.. Not sure what the jsp comment is about.
In straight javascript you could do something like this:
document.querySelectorAll('.dateSelect').forEach(item => {
item.addEventListener('click', event => {
alert(event.target.innerHTML)
})
})
<p class="dateSelect">thing1</p>
<p class="dateSelect">thing2</p>
<p class="dateSelect">thing3</p>
Related
objects ignores other array with same values.
for example
data[2018][2][25] <-- this ones gets ignored to the object
data[2018][2][22]
Code:
var date = new Date();
var data = {};
<?php $eventsNum = 3>
<?php for ($r =1; $r <= 3; $r++):?>
data[<?php echo $calendarYear[$r]?>] = {};
<?php for ($s =1; $s <= 3; $s++):?>
data[<?php echo $calendarYear[$r]?>][<?php echo $calendarMonth[$s]?>] = {};
<?php for ($t =1; $t <= 2; $t++):?>
data[<?php echo $calendarYear[$r]?>][<?php echo $calendarMonth[$s]?>][<?php echo $calendarDay[$s] ?>] = {};
//$num = $calendarDay[$s];
try {
data[<?php echo $calendarYear[$r]?>][<?php echo $calendarMonth[$s]?>][<?php echo $calendarDay[$s] ?>].push({
startTime: "<?php echo $calendarStart_time[1]?>",
endTime: "<?php echo $calendarEnd_time[1] ?>",
text: "<?php echo $calendar_description[1] ?>"
The problem is that each time through the loops you completely replace the existing object in that property. Change:
data[<?php echo $calendarYear[$r]?>] = {};
to:
if (!data[<?php echo $calendarYear[$r]?>]) {
data[<?php echo $calendarYear[$r]?>] = {};
}
and similarly for all the other initializations.
Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
I wanna make statistics in my website for the last 3 years
I want to show result like this
2016 : 159
2015 : 132
2014 : 200
I try my code (this's)
$date2 = date('Y');
$n = $date2;
for($i=$n-2;$i<=$n;$i++) {
$sql = "SELECT sum(count) AS value_sum FROM statistics where YEAR(st_date) = $i ";
$sql_sel = mysqli_query($conn,$sql);
echo '
<script>
var pieData = [
';
while($rows = mysqli_fetch_assoc($sql_sel)) {
if($i == $n-2) {
echo '{
value: '.$rows['value_sum'].',
color:"#337AB7"
},';
}
else if($i == $n-1) {
echo '{
value: '.$rows['value_sum'].',
color:"#FC8213"
},';
}
else if($i == $n) {
echo '{
value: '.$rows['value_sum'].',
color:"#8BC34A"
},';
}
echo'];
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>';
}}
?>
but this code give me just 1 one row like this
2016 : 159
I wanna see all result, any help ?
You're creating 3 charts within your for loop. If you allow php to encode the data for you, you can echo the script outside of the PHP like so:
$date2 = date('Y');
$n = $date2;
$data = array();
for($i=$n-2;$i<=$n;$i++) {
$sql = "SELECT sum(count) AS value_sum FROM statistics where YEAR(st_date) = $i ";
$sql_sel = mysqli_query($conn,$sql);
while($rows = mysqli_fetch_assoc($sql_sel)) {
if($i == $n-2) {
$data[] = array('value'=> $rows['value_sum'], 'color'=>'#337AB7');
}
else if($i == $n-1) {
$data[] = array('value'=> $rows['value_sum'], 'color'=>'#FC8213');
}
else if($i == $n) {
$data[] = array('value'=> $rows['value_sum'], 'color'=>'#8BC34A');
}
}
}
?>
<script>
var pieData = <?php json_encode($data) ?>;
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>
This should help you out:
<?php
// Store the array for the pie data within PHP at first
$js_pie_data = [];
// Define colors
$colors = [
date('Y') => '8BC34A', // current year
(date('Y') - 1) => 'FC8213', // last year
(date('Y') - 2) => '337AB7' // 2 years ago
];
$sql = "SELECT
YEAR(st_date) as `year`, -- get year from DB, makes life simpler :)
sum(count) AS value_sum
FROM
statistics
WHERE
YEAR(st_date) >= (YEAR(CURDATE())-2) -- get all records from 2 years ago to today
GROUP BY
YEAR(st_date) -- group by year so that our sum() above will work";
$sql_sel = mysqli_query($conn,$sql);
while($rows = mysqli_fetch_assoc($sql_sel))
{
// keep adding entries to the pie data
$js_pie_data[] = [
'value' => $rows['value_sum'],
'color' => '#'.$colors[$rows['year']] // based on year from DB, pick a color
];
}
echo '<script>
var pieData = '.json_encode($js_pie_data).'; // this will output a properly formatted JS array which will be understood by JS with no problem
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>';
1)You can create array in php side.
2)Then convert it as json string.
3)Define javascript variable with that json string
4)Convert it as object with JSON.parse
5)Insert it in option
<?php
$db = Array("1","2","3");
$out = Array();
$x = 0;
foreach($db as $vals){
if($x == 1){
$out[] = Array("value"=>$vals,"color"=>"#bfbfbf");
}
if($x == 2){
$out[] = Array("value"=>$vals,"color"=>"#00ffff");
}
if($x == 3){
$out[] = Array("value"=>$vals,"color"=>"#fff00");
}
if($x == 3){$x = 0;}
$x++;
}
echo "
<script language='javascript'>
var stat_str = '".json_encode($out)."';
var stat_obj = JSON.parse(stat_str);
// then you can insert stat_obj if you need object into stats
</script>";
?>
So I am sort of new to AJAX and I am trying to get this to work. What I am trying to do is create a messaging app that automatically updates every 3 seconds.
Here is my script:
function first() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').html(output);
});
}
function searchm() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').val(output);
});
}
setInterval( "searchm()", 3000 );
Here is my messageSearch.php:
<?php
session_start();
$userdb = new mysqli('localhost', 'test', '', 'social-network');
if(isset($_POST['userVal'])) {
$searchm = $_POST['userVal'];
$output = '';
if ($searchm == ''){
echo $output;
exit();
}
$uidquery = mysqli_query($userdb, "SELECT * FROM users WHERE username='$searchm' LIMIT 1");
$uid= '';
while($row2 = mysqli_fetch_array($uidquery)) {
$uid = $row2['id'];
}
$uid = 2;
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'You have no messages.';
} else {
while($row = mysqli_fetch_array($query)) {
$from = $row['p1'];
$message = $row['message'];
$time = $row['time'];
$time = date('Y-m-d H:i:s', strtotime($time));
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
while($row1 = mysqli_fetch_array($fromResult)) {
$fromFirst = $row1['first_name'];
$fromLast = $row1['last_name'];
$from = $fromFirst.' '.$fromLast;
}
$output .= '
<li>
<a href="#">
<div>
<strong>'.$fromFirst.' '.$fromLast.'</strong>
<span class="pull-right text-muted">
<em>'.$time.'</em>
</span>
</div>
<div>'.$message.'</div>
</a>
</li>
<li class="divider"></li>
';
}
$output .= '<li><a class="text-center" href="#"><strong>See All Messages</strong> <i class="fa fa-angle-right"></i></a></li>';
}
}
echo ($output);
?>
For some reason the first load works fine though the second one comes up blank. Hopefully you can help, though thanks in advance.
setInterval( "searchm()", 3000 ); should be
setInterval( searchm, 3000 );
Another error, in your PHP:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3")
should be:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=".$uid." AND `read`='n' LIMIT 3")
Lastly
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
to
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = ".$from);
I can't get this to work. I need to update the value of a column of the checked checkboxes in mysql. When I click the button it is supposed to update the value of the checked checkboxes. Here is my code for editLayout.php:
<form action="updateLayout.php" method="POST">
<input name="update" type="SUBMIT" value="Update" id="update">
<?php
$x = 'seats';
$linkID = # mysql_connect("localhost", "root", "Newpass123#") or die("Could not connect to MySQL server");
# mysql_select_db("seatmapping") or die("Could not select database");
/* Create and execute query. */
$query = "SELECT * from $x order by rowId, columnId desc";
$result = mysql_query($query);
$prevRowId = null;
$seatColor = null;
$tableRow = false;
//echo $result;
echo "<table class='map'>";
while (list($rowId, $columnId, $status, $name, $seatid) = mysql_fetch_row($result))
{
if ($prevRowId != $rowId) {
if ($rowId != 'A') {
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table><tr>";
} else {
$tableRow = false;
}
if ($status == 0) {
$seatColor = "#A6E22E";
}
else if ($status == 1){
$seatColor = "#D34836";
}
else if ($status == 2){
$seatColor = "#00A0D1";
}
echo "\n<td bgcolor='$seatColor'>";
echo $seatid;
echo "<input type='checkbox' name='seats[]' id='seats' value=".$seatid."> </checkbox>";
echo "</td>";
}
echo "</tr></table></td>";
echo "</tr>";
echo "</form>";
echo "</table>";
/* Close connection to database server. */
mysql_close();
?>
And here is my code for the jquery residing on different page (functions.js). I already included this in the header:
jQuery(function($) {
$("form input[id='update']").click(function() {
var count_checked = $("[name='seats[]']:checked").length;
if(count_checked == 0) {
alert("Please select product(s) to update.");
return false;
}
if(count_checked == 1) {
return confirm("Are you sure you want to update these product?");
} else {
return confirm("Are you sure you want to update these products?");
}
});
});
And here is my updateLayout.php.:
<?php
$db = mysql_connect("localhost", "root", "Newpass123#");
if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("seatmapping");
if(!$select_db) { echo mysql_error(); }
if(isset($_POST['update'])) {
$id_array = $_POST['seats'];
$id_count = count($_POST['seats']);
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
header("Location: editLayout.php");
}
?>
I'm using jquery 1.11.0. I know there's a lot of sql injection in here and im still using mysql but I plan to change it all once I get this to work. Any kind of help is appreciated.
Thanks in advance.
Your update query doesn't use the correct update value. You use '$seatid', which isn't declared anywhere. You should use '$id'.
Change
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
into
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$id'");
if(!$query) { die(mysql_error()); }
}