UPDATE SQL table to change timestamp - javascript

I am using php to display an SQL table. When the user selects a row on the table and then clicks a button, I want it to update the timestamp to the current time and appear on the table displayed on the webpage. The SQL query I am using works, however when I click the button, it doesn't change the values in the database, nor does it change anything displayed in the table either. The code I am using is:
I've tried CURRENT_TIMESTAMP and GetDate();, however neither seems to be what I am looking for.
So if the SignOut value is currently at 00:00, I want it to be updated to the current time.
The button appears in the following table:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>"."<td>". $row["StudentNum"]. "</td>". "<td>". $row["Name"]."</td>"."<td>".$row["Location"]."</td>"."<td>". substr($row["HomeTime"],0,-3)."</td>"."<td>".substr($row["SignOut"],11,-10)."</td>"."<td>"."<center>"."</center>"."</td>"."<td>"."</td>"."</tr>";
}
}
else {
echo "0 results";
}
The script to add the time:
<script type="text/javascript">
var _common;
$("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
_common = value;
});
function select(){
alert(_common);
<?php
$signingout = "UPDATE signon SET SignOut=CURRENT_TIMESTAMP WHERE StudentNum= '_common'";
mysqli_query($conn, $signingout);
?>
}
</script>

You are can't mix together client side code and server side code.
PHP is a server side code and can not be mixed with the javascript.
Javascript is a client side code and only lives in the browser, therefore can't be used to contact the database.
So you need to start with isolating your code. Make a new file on the server that contains the php code and call it with javascript and re-render the side with the new values.

Related

use jquery to return information from a php script that's running mysql

I know that title a bit confusing, so I'll try to explain better here.
I'm trying to create a form where a user inputs a ticket and that ticket gets assigned to a technician based off the service they provide. I have 3 text fields, username,email, Description of the problem. The next field is a select field. I populate this select field by running a php script that will query a database of services offered and return the results.
so something like
<select name="service' id= "Service" onClick="showTechnican()">
<?php include "services_offered.php"?>
</select>
When a user clicks on one of the services, I want the form to query my services_offered table and return the username(s) that provide that service in a div.
<div id="techs"></div>
I'm using a jquery script to do this
<script>
function showTechnician(){
var selectedValue = $("#Service").val();
if(selectedValue.length < 1){
document.getElementById("techs").inner.HTML = "Please Select A Service Above";
return;
}else{
var url = "technicians.php?q="+selectedValue;
$.get(url,function(data,status){
document.getElementById("techs").innerHTML=data;
});
}
}
I've also got the script technicians.php that is querying the database for me
<select name= "tech">
<?php
$q = $GET['q'];
$conn = new mysqli("localhost", "proxy_user",
"my*password","helpdesk");
if(mysqli_connect_errno()){
echo'Unable to connect to database:'.
mysqli_connect_error($conn);
}
else{
$query = "SELECT * FROM services WHERE Service_Descripton LIKE'%".$q.
"%';";
$result = mysqli_query($conn,$query);
if(!$result){
die("Invalid Query:" . mysqli_error($conn));
}
else{
while($row = mysqli_fetch_array($result)){
echo"<option value= "."{$row['User_Name']}>"."{$row['Service_Description']}".
'</option><br/>';
}
mysqli_close($conn);
}
}
?>
my issue is that when I click on a service offered, my div only shows a small empty box. Not really sure why it's not returning anything. I've got plenty of test data in the table. Made sure permissions were correct as well. I've checked the php_error_log and the query isn't failing. I'm not sure how to resolve this. Every other field on the form will insert just fine into the database.
I've attached a photo of the issue. See under "available testers" it just displays a little box.
photo of the problem
I figured it out. I can't spell, had a spelling mistake in the output of my query. Fixed it and everything worked as it should.

Don't know how to solve (Between Php and Javascript)

I don't know how to solve the variable $cat by following script.
"text" variable from Form to javascript and pass to php function to be $Categories_name and to be $cat.
I already test the $cat variable, it is not "String", it is "object", I don't understand.
But I need $cat to be "String".
when Test = "This is Cat" (3 words),
I test $cat by php str_word_count and the output is 1 (I need to correct answer 3);
I test $cat by php var_dump and no output (I need to correct answer "String").
<p id="CaTable"></p>
<script>
function CaFunction()
{
var text = document.getElementById("CategorySelect").value;
document.getElementById("CaTable").innerHTML = "<?php php_catable('" + text + "'); ?>";
}
</script>
<!-- Generate Table by php and MySQL-->
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
?>
You are confusing server side code and client side code. Your php code live on the server and can only be executed on the server. And your javascript is on your client's browser and does not know about the server (remember, php generate a text file, and only that text file is sent to the browser). if you want to use the php_catable() function from your client, you will need to do an AJAX call or to redesign your page to do a form submit (just like what Steve is proposing).
Your First Page:
Assuming CategorySelect is a dropdown select box, create a script for its onChange event and create a method="post"post form with a hidden input that goes to "generate_table.php".
<input type="hidden" name="ca_table" id="ca_table" />
You make ca_table a hidden input so php will pick up the value from it when this page gets submitted to a second page where you can generate your table using the php function.
<script language="javascript" type=text/javascript>
function CaFunction(){
documentGetElementById('ca_table').value = documentGetElementById('CategorySelect').value;
submit();
}
</script>
add this to your select dropdown:
onChange="CaFunction();"
Your Receiving Page:
So your receiving page "generate_table.php" would have
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
$category_name = $_POST['ca_table']; // cleaned up at least with suitable preg_replace etc
// and call your catable function
php_catable($category_name);
?>
So that way your result will have been posted back to the server as per comments about client side/server side by #Fluinc and answer by #litelite. To get it to do something which performs looking like innerHTML which changes a part of the page without submitting the whole page you will need AJAX, again as per #litelite's answer.
Might get marked down for being dependant on JavaScript but intended mostly to help clarify client v server.
If you want to avoid the JavaScript dependency of this script you could leave out the onChange altogether and add a submit button, then collect $_POST['CategorySelect']; assuming that is its name - ensure it has name="CategorySelect" for php as well as its Id for your css/javascript. Php gets its variable from the item's name.
To get something a bit like the effect of AJAX visually (though the page is still submitted) you could submit the page to itself using action="<?php echo $_SERVER['PHP_SELF']; ?>" on the form and have all the code on the one page. You can put the table generating code in the div where you want the table to appear - it would need a default state set, of course.
#litelite's comment regarding not using posted data directly in an sql query is also vital to prevent attack - make sure you clean it up before you use it!

Pass Selected Radio Value to PHP using onclick, then opening php file to use value in SQL query

I am pretty new to coding php and javascript but have manged to scrape my way through so far. However, I have hit a wall. I'm not 100% sure that what I'm trying to do can be done, or that I'm even attempting it in an effective way.
I have a dynamically filled table, made of rows from a SQL statement using php. On each row is a radio button, each one given a unique value based on the row number (a unique value in one of the database columns). I am attempting to program a button that enables the user to pass a selected radio button value to a separate php enabled page that will allow the user to edit the row information using the unique row value. Also, i used the confirm option, because I would also like to add an if else statement that allows the user to cancel, if the wrong row was selected (I haven't attempted that yet because I haven't been able to get the value to pass).
Page button
<input type="button" id="edit_order_button" value="Edit Order"></input>
JQuery page
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
var r = confirm("Confirm Order Number to edit: " + selected);
$.post("php/editOrder.php", {
selected1: selected
}, function(data,status) {
//alert("Data: " + data + "\nStatus: " + status);
window.open("php/editOrder.php","Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
});
});
});
PHP end destination
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
require('config.php');
$selected2= isset($_POST['selected1']) ? $_POST['selected1'] : ''; // Fetching Values from URL
echo "Selected Row number is ".$selected2.".";
mysqli_close($connection); // Connection Closed.
?>
I have tried a few things but have so far been unsuccessful in getting the new window to load with the value of the radio button passed. Currently, the window loads, but the new window only displays the echo text, no variable. When I run with the alert popup, the data shows me the value of the selected row but it does not seem to be posting to the new page prior to the window.open command. Any tips would be appreciated, or if i'm approaching the problem from a wrong angle, any insights would also be great. I have also tried debugging, thinking I was missing a parentheses or semicolon but I wasn't able to find anything. Thanks
Looks to me like you can get rid of the post statement altogether and just pass the selection to the newly opened window.
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
// only open window if order okayed
if ( confirm("Confirm Order Number to edit: " + selected) ) {
window.open("php/editOrder.php?selected1=" + selected,"Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
}
});
});
php/editOrder.php:
$selected2 = $_GET['selected1'];
echo "Selected Row number is $selected2.";

How do I display random text and image from PHP form on refresh?

I'm a fairly new programmer and I'm currently working on creating a program for a web-based art exhibit that would will display a random image and text using data from a PHP form which requires inputs for both.
I will need to create a PHP form that gathers text and a picture from the visitor.
Example PHP page:
*What is your name?* = Max
*Upload photo.* = pic.jpg
The finished project would be a webpage that - on refresh - would display the image and the text gathered from the PHP form randomly. So on refresh the page would display a random text input (I.E Max, Alan, Mark, etc.) and a random picture (I.E pic.jpg, pic1.jpg, pic2.jpg) I'm guessing from a MySQL database.
The page, on refresh, would therefore display something like this:
Max / pic.jpg
REFRESH
Alan / pic3.jpg
REFRESH
Mark / pic2.jpg
And so on...
This is what I have so far:
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$pic=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("mysite.com", "username", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$pic')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Any help on this would be much appreciated!
Thank you!
Pull out the data using
SELECT * FROM table ORDER BY RAND() LIMIT 0,1;
Then pull out the
<?
$sql=mysql_query("SELECT * FROM table ORDER BY RAND() LIMIT 0,1;");
while($row=mysql_fetch_array($sql)){
$name=$row['name'];
$imagename=$row['imagename'];
//write the logic here use echo or close and open php using <? and ?>
//giving an example
echo "Name: ".$name."<br>";
echo "<img src='directory/'".$imagename." width='100' height='100'>";
//OR other way
?>
Name : <? echo $name;?><br>
<img src="directory/<? echo $imagename;?>" width="100" height="100">
<?
}
?>
First you will need to create the html form. I assume you have some basic knowledge about this, so let's assume you do it and post it to post.php. Here you'll need to:
Handle the image.
Insert the name and image reference into the database.
Redirect the user to the landing page (important to avoid refreshing issues like "want to send your data again?").
Fetch a random entry for the database and display it to the user on the landing page.
A few tutorials:
Upload Images Using PHP.
Insert data into database
Pick up a random record from the database Disclaimer: my own question over 1 year ago
However, it's not a 'trivial' task. It'd take few days to someone familiar with the languages, with someoone who is not maybe 1 week provided you start from the ground up.

Execute script when select option is changed

I have a html form which includes a dynamically created dorpdown list. The dropdown list contains the names of newsletters which are stored in my MySQL database. What I want the dropdown list to do is: When I select a newsletter an other php script will activate which will take the data from the newsletter in my DB and writes it to a .txt file. The codes I currently have is:
The dropdown list:
<?php
echo "<select id=\"NieuwsbriefSelect\" name=\"show\">";
echo "<option size =30 selected>Select</option>";
if(mysql_num_rows($sql_result))
{
while($row = mysql_fetch_assoc($sql_result))
{
echo "<option value=\"$row[Titel]\">$row[Titel]</option>";
}
}
else {
echo "<option>No Names Present</option>";
}
?>
And the write script:
<?php
$title = $_REQUEST["show"];
mysql_connect('localhost','root','root');
mysql_select_db('NAW') or die (mysql_error());
$strSQL = "SELECT Content from NAW.Mail where Titel = '$title' ";
$sql_result = mysql_query($strSQL);
$row = mysql_fetch_assoc($sql_result);
$file = 'nieuwsbrief.txt';
$current = $row["Content"];
file_put_contents($file, $current);
?>
I do not want the page to redirect to the write script but just to execute it (I hope you get this^^). Is this possible using the HTML onChange Event or do I have to use javascript? Any help would be great and if you have a question about my code just ask in the comments!
NOTE!
I know I shouldn't be using Mysql_* and That I am vulnerable to sql injection but that is not the point.
You need to define a onchange event on your SELECT option and inside this onchange event, you can redirect to another page with selected item OR do an AJAX call to another PHP script
Unfortunately what you are asking is not possible without JavaScript. PHP is a server side language and therefore cannot be run, without a call from the client-side browser. You're best bet would be to use ajax in conjunction with the JavaScript onchange event. When the change event occurs, fire an ajax call off to the server to run the script with the selected option. This is the only way to do what you're asking without a page reload or redirect.

Categories