I have some php code that writes to my database (phpmyadmin) into a table called b83hi_out_of_office. I am entering a custom message and the username from an html form.
The data does get written to the table, but it also is adding extra blank rows.
Does anyone know why this is and how I can fix it?
<form method="post" action="">
<p>Out of Office Message</p>
<p><input type="radio" name="RadioGroup" value="off" id="RadioGroup_0" checked="checked"> OFF<br>
<input type="radio" name="RadioGroup" value="on" id="RadioGroup_1"> ON
</p>
<p><label>Custom Out of Office Message</label>
<input type="text" name="custommessage" size="30" maxlength="25"/></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
<?php
$message = $_POST[custommessage];
//get user info
$user = JFactory::getUser();
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Insert columns.
$columns = array('username', 'message');
// Insert values.
$values = array($db->quote($user->username), $db->quote($message));
// Prepare the insert query.
$query
->insert($db->quoteName('b83hi_out_of_office'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->execute();
?>
My guess would be that your script is running every time the form is loaded (So you get a blank row inserted when you load the form, then the correct row inserted when you submit it.).
The easiest way around this would be to check that a $_POST value is set.
Example:
<?php
if(isset($_POST['submit'])) {
$message = $_POST[custommessage];
//get user info
$user = JFactory::getUser();
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Insert columns.
$columns = array('username', 'message');
// Insert values.
$values = array($db->quote($user->username), $db->quote($message));
// Prepare the insert query.
$query
->insert($db->quoteName('b83hi_out_of_office'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->execute();
}
?>
With that change, you are not inserting any data unless the form has been sent.
A better option would be to have your php script as a seperate file, and having the action="" of the form pointing to that file.
Related
So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
so I've finally figured out how I can get values from my mySQL-db into a dropdown form in PHP. My problem is, how can I use/work with the option that was selected by the user?
My goal is a functioning email-signature generator. I want the user to be able to insert unique data like their name, and select the office where they work from the dropdown form. After they hit the submit button, they should then be lead to the next site that displays their name with the signature for the selected office.
The name is no problem, that is only a simple html-form with a post method, I know how I can retrieve and access that.
But how can I work with the option that was selected by the user in the dropdown?
After selecting an option and hitting submit, the whole "row" in the mySQL-db should be displayed, in formated form.
My current situation is that the dropdown shows the correct values from the mySQL-db, and the two name fields, that are also working as they should.
The name of the mySQL database is "firmen", the name of the column I use is "niederlassung".
I'm happy to provide more information if needed.
My code:
[...]
<form action="php-verarbeitung.php" method="post">
<div>
<label for="1">Vorname: </label>
<input type="text" name="vorname" id="1" value=""><br><br>
</div>
<div>
<label for="2">Nachname: </label>
<input type="text" name="name" id="2" value=""><br><br>
</div>
<input type = "submit" name = "button" value = "Senden"><br><br>
<?php
// Establish mySQL PDO Connection
$server='mysql:host=*****.com.mysql;dbname=*****'; // Host and DB-Name
$user="******"; // Username
$password="*****"; // Password
$pdo=new PDO($server, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Write out the query
$query = "SELECT niederlassung FROM firmen";
// Execute it, or let it throw an error message if there's a problem
$stmt = $pdo->query($query);
$dropdown = "<SELECT name='firmen'>";
foreach ($stmt as $row) {
$dropdown .= "\r\n<option value='{$row['niederlassung']}'>{$row['niederlassung']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
</form>
</body>
</html>
Thanks for any help in advance!
you are passing the variables through the form to php-verarbeitung.php. On that page you can load the content based on the $_POST variables that are sent through the form. so you can query the DB again on the second page to get the info you need, and present formated html using the values from the form passed through the post array, in your case
$_POST['vorname'], $_POST['name'] and $_POST['firmen'] should all be accessible when the php-verarbeitung.php page is called using your script above.
Hi I have a html form button called delete. Next to the button is an input area. The logged in user will enter a number corresponding to the ID then press delete. It should delete the row corresponding to that ID.
For some reason it doesn't work.
This is my html form:
<h3 class="block-head">Delete Job</h3>
<form action="deletejob.php" method="post" class="basic-grey">
<label>Please Enter Job ID</label><input type="text" name="idnum" id="id"/><br>
<input type="submit" name="delete" value="delete"/>
</form>
This is my php code:
mysql_connect("********", "root", "******")
or die("Connection Failed");
mysql_select_db("jobslist")or die("Connection Failed");
$idnum = $_POST['id'];
$query = "delete from jobs_list where idnum = '".$id."'";
if(mysql_query($query)){ echo "deleted";}
else{ echo "fail";}
I know about switching to mysqli and that...I just want to see if this method works first.
thanks.
the name of your input is idnum yet you are looking in the $_POST array for id and in your query using the variable $id when you declare $idnum in the line previous.
$idnum = intval($_POST['idnum']);
$query = "delete from jobs_list where idnum = '".$idnum."'";
PHP receive the data via $_POST as an array of input elements with the key as the NAME of the input field, so you have to change this line:
$idnum = $_POST['idnum'];
You can also change the input name and don't change the php code:
<input type="text" name="id" id="id"/>
It's a typical mistake, don't worry too much about that :P
You should change the POST value.. and then try
$idnum = $_POST['idnum'];
Change the HTML, update the input type id to:
id="idnum"
then, update the PHP query while fetching the post value to:
$idnum = $_POST['idnum'];
It should work.
$user_name = "xxx";
$password = "xxx";
$database = "xxx";
$server = "xxx";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$randWordDesc = mysql_query("SELECT * FROM words ORDER BY RAND() LIMIT 1");
$db_field = mysql_fetch_assoc($randWordDesc);
if(isset($_POST['new'])){
$unaltered = $db_field['word'];
$noA = str_replace("a", "b", $unaltered);
}
if (isset($_POST['edit'])){
global $noA;
$noR = str_replace("r", "c", $unaltered);
}
?>
<form action="http://xxx" method="post" ><br><br>
<input type="submit" value="edit current" name = "edit" id="gobutton">   
<input type="submit" value="new" name = "new" id="gobutton">
</form>
The code I have now will pull up a new word if the 'new' button is selected and replace the 'a''s with 'b''s. I want the 'edit' button to take the exact same word just pulled up and replace the 'r''s with 'c''s. However, as the code is now, the edit button will either pull up a new word or not pull up anything at all.
How could I get the edit button to edit the query that the 'new' button pulled up? I'm not sure how I could store it by the id, but all the columns have an id number, if that helps. Also I know that "SELECT * FROM words ORDER BY RAND() LIMIT 1" is really bad form, but that's an issue I want to tackle after this problem. Thanks for your help.
As the first query returns only one result, you could take the primary key column data of the resulting row and store it in a hidden input element on the page. When you use the edit button, you would then pass the hidden input field value which can be used to pull the same record as you pulled with the most recent get new word function call.
Consider something like the following:
<form action="http://xxx" method="post" ><br><br>
<input type="hidden" value=<?php echo $db_field['primary_key']; ?> name="record_id">
<input type="submit" value="edit current" name = "edit" id="gobutton">   
<input type="submit" value="new" name = "new" id="gobutton">
</form>
The id will be passed with your post, which you can then check for and use in a select query to get the record. Just be sure to be careful with data handling. Consider updating to a current API (mysql~ functions are deprecated) and prepared statements.
I am beginner in PHP and I am trying to figure out how to link a form to a PHP script.
Basically, I am creating a search bar where users can search the database for employee details based on their ID. The script would then retrieve the results from the database based on the ID.
Code:
<form action="results.php" method="get">
Employee ID: <input type="text" name="name"><input type="submit">
</form>
<?php
// connect to the mysql database server
$db = new PDO('mysql:host=localhost:3306;dbname=db_test14;charset=utf8', 'root', 'password');
// Prepare the statement (the basic outline of your query)
$st = $db->prepare('SELECT * from techsols_employee WHERE id = ?');
// Actually execute the query, putting in your id
$st->execute(array($employee_id));
// Get the actual employee details out of the result
$employee = $st->fetch();
?>
Would appreciate some help on this.
<form action="results.php" method="GET">
Employee ID: <input type="text" name="name"><input type="submit">
</form>
<?php
if (isset($_GET['name'])) {
//! Some validation and sanitising of the _GET here
$employee_id = $_GET['name'];
// connect to the mysql database server
$db = new PDO('mysql:host=localhost:3306;dbname=db_test14;charset=utf8', 'root', 'password');
// Prepare the statement (the basic outline of your query)
$st = $db->prepare('SELECT * from techsols_employee WHERE id = ?');
// Actually execute the query, putting in your id
$st->execute(array($employee_id));
// Get the actual employee details out of the result
$employee = $st->fetch(PDO::FETCH_ASSOC);
echo $employee['name'];
}
?>
What have I changed?
GET to POST (Difference) - Edited after comments back to _GET.
$employee_id to equal _POST
Checks if you've input by isset
Changed the fetch style to PDO::FETCH_ASSOC
Try this
Employee ID:
<?php
if(count($_GET)){
$emp_id = intval($_GET['name']);
//! Some validation and sanitising of the _POST here
// connect to the mysql database server
$db = new PDO('mysql:host=localhost:3306;dbname=db_test14;charset=utf8',
'root', 'password');
// Prepare the statement (the basic outline of your query)
$st = $db->prepare('SELECT * from techsols_employee WHERE id = ?');
// Actually execute the query, putting in your id
$st->execute(array($emp_id ));
// Get the actual employee details out of the result
$employee = $st->fetch();
}
check out a sample example in w3schools http://www.w3schools.com/php/php_ajax_database.asp
Modify it to make it work for your case.