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.
Related
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.
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.
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!
I have a form.php which adds username selected from dropdown select, and user payments received into database. After inserting values by going to add_form.php, it comes back to form.php. I have sent the username from add_form.php to form.php by using below code
$result=mysql_query($sql);
if($result==1){
echo '<script language="javascript">';
echo 'alert("Payment added successfully");';
echo 'window.open("form.php?name='.$name.'", "_self");';
echo '</script>';
}
Now problem is that, how can I use this get parameter to select the passed value into dropdown automatically? I want the end user of the application to select a name once and add multiple payments, i.e., selected name should be there even after payment is added into db
I am not sure what you want but if filling up the select with options dynamically (with some js variables) is what you want then you can try something like.
$("#id_something").empty();
$("#id_something").append('<option selected="selected" value='+somejsvariable+'>'+someotherjsvariable+'</option>');
Hope it helps.
I am trying to get this to allow the user to click on a link, which will then change the value of what is submitted in the SQL SELECT Statement, if that makes sense.
My Code so far:
<div class="Tabs" >
<?php
require 'database/connect.php';
$sql = "SELECT DISTINCT Week FROM PMWUpdates";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo '<a class="weeks"> Week' . $row{'Week'} . '</a>';
}
?>
</div>
<div class="Pages">
<?php
require 'database/connect.php';
$sql = "SELECT * FROM PMWUpdates WHERE Week='1'";
?>
</div>
I want the value of SELECT * FROM PMWUpdates WHERE Week="'1'"; to be what link the user has clicked on above, not just always 1. So if the user clicks on the link 2, the SQL changes to SELECT * FROM PMWUpdates WHERE Week="'2'";
I am basically trying to accomplish this, but instead, I want to display the number of tabs, based on the number of weeks in a database, and then, each week will display data from the database about that particular week.
Any help is appreciated.
Thank You
Your statement should be like this...
$sql = "SELECT DISTINCT Week FROM PMWUpdates";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo '<a class="weeks" href="$row['Week_link']"> Week' . $row['Week'] . '</a>';
}
If you mean dynamically changing data on a page which requires PHP to be processed, you have to take a look at AJAX. You can't do it this way, once your script is loaded, there is no more php, only HTML.
If you don't want to use AJAX, you will have to do it in 2 pages. First display links, then display your data related to whatever was selected.
The MySQL extension you are using is deprecated (>= 5.5). Use MySQLi or PDO instead.
What you are trying to accomplish is that where your "2" is listed, should change with the use of a variable. As you want to do it via Javascript, you will need a click event on those links which then submits the variable via AJAX.