PHP form unable to update database - php

Hi guys I'm having trouble with my PHP code. Unable to update the database when I submit the form. I'm trying to update the new price.
Here's my PHP code:
<?php
if(isset($_POST['update']))
{
# $db = new mysqli('localhost','XXXX','XXXX','XXXX');
if(! $db )
{
die('Could not connect: ' . mysqli_error());
}
$price = $_POST['price'];
$sql = "UPDATE bookprice ".
"SET price = price " ;
mysqli_select_db('books');
$retval = mysqli_query( $sql, $db );
if(! $retval )
{
die('Could not update data: ' . mysqli_error());
}
echo "Updated Price successfully\n";
mysqli_close($db);
}
else
{
?>
Form code:
<form method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input name="update" type="submit" id="update" value="Update Price">
<input name="price" type="text" id="price">
</td>
</tr>
</table>
</form>
Still in the process of grasping PHP. Any form of help is greatly appreciated!

You're not using the $price variable to set the price column to.
Use "SET price = $price " ;
or inside quotes "SET price = '$price' " ;
What you're doing right now is "set the price column equals price column" instead of the intended value taken from the POST variable $price. More on this at the end of my answer under Footnotes.
Another thing:
$retval = mysqli_query( $sql, $db );
you need to reverse the query and DB connection:
$retval = mysqli_query( $db, $sql );
In mysqli_, the connection comes first, then the query's variable.
Plus, use:
$db = new mysqli('localhost','XXXX','XXXX','books');
You're using all four parameters in your DB connection, so you can drop:
mysqli_select_db('books');
since you're not doing anything with it, and simply add books as the DB's parameter.
Using the fourth parameter with the DB's name, is the same as using mysqli_select_db with the DB's name and connection variable, which is something you are not using.
Read the manual http://php.net/manual/en/mysqli.select-db.php
You also have a missing closing brace in
else
{
?>
if you don't have anything after that, do:
else
{
echo "Fail";
}
?>
Footnotes:
If your price contains a dollar sign, or a dot or mix of those, or something else that SQL does not agree with (which am under the impression it could), you will need to wrap it in quotes:
$sql = "UPDATE bookprice SET price = '$price' " ;
or
$sql = "UPDATE bookprice SET price = '".$price."' " ;
If your column is an int type, then you can use
$sql = "UPDATE bookprice " . "SET price = ".$price;

remove #
$db = new mysqli('localhost','XXXX','XXXX','XXXX');
and update the query
$sql = "UPDATE bookprice ".
"SET price = ".$price ;

Give this a try:
<?php
if($_POST['update']){
$db = new mysqli('localhost','XXXX','XXXX','XXXX'); // remove '#'
if(!$db){
die('Could not connect: ' . mysqli_error($db)); // Needs the database connection
}
$price = $_POST['price'];
$sql = "UPDATE `bookprice` SET `price` = '$price'"; // Use the variable $price
// mysqli_select_db('books'); // This should already be set in the new mysqli();
$retval = mysqli_query($db, $sql); // Turn this around;
if(!$retval) {
die('Could not update data: ' . mysqli_error($db)); // needs the database connection
} else {
echo "Updated Price successfully\r\n"; // \r\n will always work \r or \n alone will not always work
}
mysqli_close($db);
}
else {
echo 'There was no post';
}
?>
HTML:
<form action="" method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input name="update" type="submit" id="update" value="Update Price">
<input name="price" type="text" id="price">
</td>
</tr>
</table>
</form>
Links:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
http://nl3.php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/function.number-format.php (since you are working with a price this may come in handy)
You should also consider the use of mysqli_real_escape_string() so:
$price = mysqli_real_escape_string($db, $_POST['price']);

Well actually if you concat your queries with $parameter directly, it opens up a security risk
$price = $_GET["price"] (from the URL)
$price = $_POST["price"] (from the FORM Post)
UPDATE bookprice SET price = '$price'
You should try using prepared statements like
Update bookrprice set price = :price
or
Update bookrprice set price = ?
and then create a associate key value pairs to security and pass it in to your query. This is why it is not recommend to use mysql_query and rather mysqli or PDO methods.
then your would pair the above statement by
execute(array(":price"=>$price))
or
execute(array($price))

Related

Search by PHP Mysql

I want to get some variables from a form and i will use those variables to make a search bar for example:
$var=$_POST['var']
I want to put this variable in a request like this:
$SQL = 'SELECT * FROM Table ORDER By $var'
Any suggestions please? How can I transform this request to a dynamic request? thank you :)
The code is:
<form>
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
<?php
$variable = $_POST['variable']
sql = 'SELECT * FROM Total ORDER BY $variable';
?>
Please refer to PDO and for order by review.
your select query would be
SELECT * FROM yourtable ORDER BY DATABASE_FIELD;
At first,
use method="POST" and action="file.php" (but action is not strictly needed, in some cases like processing by AJAX)
<form method="POST" action="file.php">
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
At second you need sanitize input taken from form (it means, you have to eliminate anything that would harm your pages - with this PDO or else layer can help).
At third, you need to rewrite
sql = 'SELECT * FROM Total ORDER BY $variable'
to
sql = "SELECT * FROM Total ORDER BY $variable"
or
sql = 'SELECT * FROM Total ORDER BY '.$variable
because else used variable would be used as is written, instead its content (given by form).
Since you're new it would be wise to embed some good practices from the start. Documentation for reference would be PDO and Prepared Statements.
An example PDO tutorial can be found on W3Schools, along with a tutorial on handling form data with PHP.
This is an example of a simple search
PHP:
<?php
$search = $_POST["search"];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `profile` WHERE `email`='$search'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
HTML:
<form action="profile.php" method="post">
<input type="text" name="search"><br>
<input type="submit">
</form>
Hope it helps

sql php results and search

I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand

PHP and SQL Server Express to retrieve and show data

I am looking to take a PHP page to retrieve data based on the selection from a drop down list, then show the results based on that selection. I am not even sure where to begin except my connection to the database. I do also know that I have to have a query statement, like I would in SQL, which here is a little bit of that:
$sql = "SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = 'bs1441'";
The bs1441 is just an example of one option that would be in the drop down list. I am not sure what I would put there for it to put in there automatically from the list.
Thanks for the help in advance. Sorry if there is not enough information to go on, but not sure what even would be needed at this point.
EDIT:
This is what I have so far:
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$result = sqlsrv_query( $connection,
'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM Logs
WHERE (ForteID = $ForteID)',
array($ForteID));
while($row = sqlsrv_fetch_array($result))
{
echo($row['ForteID'] . ', '.
$row['Disposition'] . ', '.
$row['appNumber'] . ', '.
$row['Finance_Num'] . ', '.
$row['Num_Payments'] . ', '.
$row['ACH_CC'] . ', '.
$row['Notes'] . ', '.
$row['Date']);
}
sqlsrv_close( $connection);
?>
Then when I look at the page it throws this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\cslogs\getlog.php on line 46
Line 46 is this line:
echo($row['ForteID'] . ', '.
Let me know if that helps!
A couple steps here:
First you need to submit your form with the selection in. I'm not going to go over form submission here but look into it.
once you submit the form you will need to get the value of the drop down and assign it to a variable.
$value= $_POST['value'];
Note: This is a basic example so I didnt add in regex or anything like that.
Once you have your variable ($value) you can then put it in your SQL
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
So here we are processing the query. $dbc is the variable that I chose to represent my database connection and the "or die" part will let me know if the query is valid or not.
Once you have a working query you can then summon the data pulled into an array:
while ($row = mssql_fetch_array($sql)) {
And then you need to assign the results of your query to a variable.
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
The capital words are the titles of the columns in your sql table. After you have them assigned to variables you can do whatever you want to them provided they are inside the while loop.
$value= $_POST['value'];
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
while ($row = mssql_fetch_array($sql)) {
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
echo $result1;
echo $result2;
}

How to use the form value in php function?

I am newbie to php.I have coded auto-complete text box using php,and i have a submit button.i have not given form action.
This is the HTML form code that i used for autocomplete textbox.this autocomplete textbox selects the value
<form method="post" autocomplete="off">
<p>
<b>Theater Name</b> <label>:</label>
<input type="text" name="theater" id="theater" />
</p>
<input type="submit" value="Submit" />
</form>
I have another php function that retrieves the values based on where clause.in the where statement i want to use selected value from form.
for ex: select address from theaters where theater_name ="form value"
How to use the form value in php function?can any one help me?
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theter
WHERE theater_name="<!-- This could be value that we get after clicking submit button-->);
while($row = mysql_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
?>
Thanks in advance......
You could get the value from $_POST by $_POST['theater'].
And note, you should not use this value directly in the sql, you need to escape it to prevent sql injection.
$theater = mysql_escape_string($_POST['theater']);
$result = mysql_query("SELECT * FROM theter WHERE theater_name='$theater'";
Last, you could take a look at PDO, which is suggested over the old mysql_* functions.
First, change your submit button code to the following:
<input name="submit" type="submit" value="Submit" />
Now, this is the code you should use for the query:
<?php
if (isset($_POST['submit'])) {
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theater
WHERE theater_name='" . mysql_real_escape_string($_POST['theater']) . "'");
while($row = mysql_fetch_array($result))
{
echo $row['theater_name'];
echo "<br />";
}
}
First, I check that the user submitted the form. Then, I escape the data he has submitted and inserting it into your query.
* NOTE: All of what I've wrote is based on the assumption that the code is executed after the form is submitted.
* ANOTHER NOTE: You should read about using PDO rather than MYSQL functions.
First and foremost, try using mysqli instead of mysql (mysqli_query, mysqli_connect). There are numerous security / speed advantages to using it and it has pretty much the exact same functionality.
While the above answers mention using $_POST['theater'] (the name of your input), be SURE to escape your post before putting it into your query.
$con = mysqli_connect("localhost","root", "YOUR PASSWORD HERE", "YOUR DATABASE HERE");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// No need for this, please see the updated mysqli_connect as the 4th parameter selects your DB
//mysqli_select_db("theaterdb", $con);
// Please notice the last parameter of the mysqli_real_escape_string is your Input's POST
$query = "SELECT * FROM theater WHERE theater_name=".mysqli_real_escape_string($con, $_POST['theater']);
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
$_POST["your_variable_name"] // for POST
$_GET["your_variable_name"] // for GET
For in-depth information please go to: http://www.php.net/manual/en/language.variables.external.php

sending multiple records to MySQL from multiple select box

I'm trying to insert multiple rows into a MySQL table depending on the number of options selected from a multiple select box. currently it is inserting one row (regardless of how many options are selected) but the 'strategyname' column is empty each time.
Any ideas on how to insert multiple rows and why the values of the options aren't being sent to the table?
Here is the form:
<form method="POST" action="update4.php">
<input type="hidden" name="id" value="1">
<p class="subheadsmall">Strategies</p>
<p class="sidebargrey">
<?php
$result = mysql_query("SELECT strategyname FROM sslink WHERE study_id = '{$_GET['id']}'");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategyname = $row['strategyname'];
echo $strategyname.'<br />';
}
?>
<p class="subheadsmall">Add a strategy... (hold down command key to select more than one)</p>
<select name="strategylist" multiple="multiple">
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<option value="' . $strategylist . '" >' . $strategyname . '</option>' . '\n';
}
?>
</select>
</p>
<input type="submit" class="box" id="editbutton" value="Update Article">
</form>
And this is what sends it to the database:
<?php
$id=$_POST['id'];
$test=$_POST['strategylist'];
$db="database";
$link = mysql_connect("localhost", "root", "root");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
//for($i=0;$i<sizeof($_POST["test"]);$i++)
//{
//$sql = "insert into tbl_name values ($_POST["test"][$i])"; }
//sql = "INSERT INTO table_name VALUES ('" . join(",",$_POST["test"]) . "')";
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) VALUES ('$id','" . join(",",$_POST["strategylist"]) . "')")or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>
Couple of points:
your select needs to be named strategylist[] in order to tell PHP that it will contain an array rather than a single value
Your insert code then needs to iterate over that array, creating a new insert for each element it contains, unless (as it seems) you want all those options to be concatenated into a single row's field.
At the moment, your form only returns a single option (from PHP's perspective), so it's only going to insert a single row.
To iterate over the array, use something like this:
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
Two things:
If you view the source of page with the multiple select in it, can you see the <option value="something"> lines there? Are the values empty? It seems strange to me that at the top of your file you are using $row['strategyname'] and later you are using $row['name']. I suspect this may be the cause of the empty StrategyName column.
To handle multiple selections, you should specify the select tag as
<select name="strategylist[]" multiple="multiple">
The extra [] tells PHP to form an array with all of the selections in it. You can then loop over the array like:
$strategylist = $_POST['strategylist'];
for ($i = 0; $i < count($strategylist); $i++) {
$strategyname = $strategylist[$i];
// Insert a record...
}
// first you need to define your output as one variable if you don't like the loop
if($_POST){
$sum = implode(", ", $_POST[select2]);
echo $sum.".";
}
// the variable sum is the one you are seeking for you can insert it to the database
// if you want to enter every peiece of the array in a new field you should use
// different select names

Categories