How to store random MySQL query for later use? - php

$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">&nbsp&nbsp&nbsp
<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">&nbsp&nbsp&nbsp
<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.

Related

button to call php to delete mysql row via ID

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.

Form session not working when multiple users use it

i need an help from you all.
i had created an form using PHP. it's a school application registration form. it has one page only.
i need to generate registration number(session id used as registration number here) for everyone who opens the form.
instead of creating a session i have used ID for all. that is when some one submits the form, it checks the DB and if the registration number is there, it will increment one value and add the current form to DB.
my code here
<td>Application No : <input type="hidden" name="disablusr_dummyid" autocomplete="off" style="background:#f0efed;" value="00<?php
include('config.php');
$q="select MAX(auto_gen_id) from application_form";
$result=mysql_query($q);
$data=mysql_fetch_array($result);
$max_val=$data[0];
echo $max_val+1;
?>"/>
<input type="hidden" name="applicant_id" autocomplete="off" value="00<?php
include('config.php');
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
echo $erfdqwe+1;
?>" />
<input type="hidden" name="txt_applicant_id" style="display:none;" autocomplete="off" value="<?php
include('config.php');
$werqw = "select MAX(auto_gen_id) from application_form";
$resultghasw = mysql_query($werqw);
$dataqsax = mysql_fetch_array($resultghasw);
$erfdqweqti = $dataqsax[0];
echo $erfdqweqti+1;
?>" /></td>
but what is happening is when multiple users are using the form same session ID is generated and only one user is able to save the form and it reflects in DB. other forms are being not submitted and not added to DB.
help me in this error.. thanks in advance.
The solution here is not the use the hidden fields for the IDs :
At this moment u have something like this :
"INSERT INTO (id, ..., ...) VALUES('".addslashes($_POST['applicant_id']."', ...)
You should refactor your logic to calculate the id afterwards meaning that u drop the hidden fields and do this :
<?php
if (!empty($_POST)) {
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
$new_applicant_id = $erfdqwe+1;
}
And then use the $new_applicant_id into the INSERT sql.
On a sidenote your code is vulnerable for SQL injection and is using outdated functions.
You should try to move to mysqli or PDO and preferable use prepared statements

After form submit get the id from databse of last record

I need help for my web service project where user create an order when submit the order form, Driver get notification with accept or reject the order and when he accept order details list display to him. these all process done with order form submission. my all coding working fine. I don't understand where from get id of current order list. plz give solution. thx
<?php
if(isset($_POST['order_form']))
{
mysql_connect('localhost','root','');
mysql_select_db('live_help');
$user = $_POST['user'];
$password = $_POST['mobile'];
$password = $_POST['address'];
$password = $_POST['order_item'];
$password = $_POST['price'];
$sql= mysql_query("insert into `json_web`(user,mobile,address,order_item,price) values('$user','$mobile','$address','$order_item','$price')");
if($sql)
{
echo 'Value Saved';
}
}
?>
<form name="order_form" action="" method="post">
<input type="text" name="user">
<input type="text" name="mobile">
<input type="text" name="address">
<input type="text" name="order_item">
<input type="text" name="price">
<input type="submit" name="field1" value="Submit" />
</form>
use mysql_insert_id(); to grap the last insert id. Take a look for more information
mysql_insert_id()
Warning:
mysql_* is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
After your mysql_query(); you can do this:
$id = mysql_insert_id();
mysql_insert_id(); retrieves the ID of the last inserted element to the database.
Use mysqli_insert_id() as from documentation
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
In order to use mysql_insert_id() you need to add another field into the database table so you can have distinct order id for each order.
Perhaps you already have it, if not, add it:
ALTER TABLE `json_web` ADD order_id INT(10) NOT NULL AUTOINCREMENT;
Then just select from database, use mysql_insert_id()
Cheers

php code writing to phpmyadmin

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.

SQL text boxes with dynamic information / auto fill text boxes

I am trying to make a webpage that connects to my SQL database and fetches information from a table and place it into a text box. The information it fetches is dependent on what is entered into another text box. Essentially its an "autofill" of information. I was curious whether this was possible.
To create a better understanding here is a layout of text boxes:
<html>
<head>
<?php
$con = mssql_connect("abc", "123", "password");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM FormData");
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<form action="#">
<p>Enter ID</p>
<input type="text" name="ID"/>
<input type="text" name="NAME"/>
<input type="text" name="LASTNAME"/>
<input type ="button" value="submit" onclick="check(ID)" />
</form>
</body>
Here an ID would be entered into a text box and then once the submit button was pressed, it would fetch the rest of the information from my sql database into the next boxes. I don't even know whether this is possible, whether I can use Javascript in conjunction with this or something. I searched but couldn't find much help on the subject.
I'm not even sure if its possible to do "if" statements within SQL - whenever I try I end up with a 500 error due to improper syntax.
If I understand you correctly, all you need to do is on the submission of the form capture the ID they entered.
If the ID has not been submitted yet (either their first time hitting the page, or they failed to enter an ID) you should not perform any query and create a blank $row array like so:
$row = array("ID" => "", "NAME" => "", "LASTNAME" => "");
You should then fill your form fields using this array <input type="text" name="NAME" value="<?php echo $row['NAME']; ?>"/>.
If the ID has been submited you then use this ID in your SQL query "SELECT * FROM FormData WHERE ID = $_POST['ID']" (Note: This is an example. You will need to escape the POST data to prevent SQL injection).
You need to then pull this result into your $row array $row = mysql_fetch_row($result) which in turn is used by your fields to populate the value.
This entire procedure could be done with AJAX so that you don't have to perform a full page submit however based on your example the solution I have provided should be good enough.

Categories