I'm trying to delete a row in mysql based on the selection I make in a combox, I know this is deprecated but it's just for personal use. By the way
I have something like this:
<form method="get" action="">
<?
require ('link.php');
mysql_select_db('proesi',$link) or die(mysql_error());
$rs = mysql_query("SELECT * FROM curso") or die(mysql_error());
echo "<select name='combo'>";
while($row2 = mysql_fetch_array($rs)){
echo "<option value='".$row2["id"]."'>".$row2["curso"]."</option>";
}
echo "</select>";
?>
<input type="submit" name="borrar" value="ELIMINAR" />
</form>
<?
$combos = $_get['combo'];
if (isset ($_post['borrar'])){
print $combos;
require ('link.php');
mysql_select_db('proesi',$link) or die(mysql_error());
mysql_query("DELETE FROM curso WHERE curso= //here i need to get the value, i'm trying to use the "id" field since it is unique// ") or die (mysql_error());
mysql_close($link);
}
?>
the select has a name. When the form is submitted, you can get it's value with $_GET['combo']
Then, in your sql,
$selected_id = $_GET['combo']; //sanitize this!!!
mysql_query("DELETE FROM curso WHERE curso= '$selected_id' ") or die (mysql_error());
of course you have to make sure the value entered into the sql is sanitized and secure from sql injections, but since you are learning, you will get to it later.
Related
I am creating a simple custom search form. This form searches the table 'oc_product' where i created a new column 'gcode'. I have inserted a sample data in this column for one of the products. Is it necessary to make a new db/mysql connect in php within a new tpl file i created just like 'information/contact'. I call this 'gcode/gcode'.
I tried but unable to get result form the search. It redirected to index.php.
My code is:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("localhost", "username_demo", "pwddemo123") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("db_demo");
//-query the database table
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%" . $name . "%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$gcode =$row['gcode'];
//-display the result of the array
echo '<span>'."This product is genuine".$gcode.'</span>';
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
Any example to search a column and fetch data from a column.
Don't quite understand your question. Do you want to fetch data from ONE column? Also use mysql_fetch_assoc instead mysql_fetch_array
And replace $_GET with $_POST
Also your select statement is wrong, so do this:
<?
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%$name%'";
$result = mysql_query($sql);
$results = mysql_num_rows($result);
for($i=0; $i<$results; $i++)
{
$row = mysql_fetch_assoc($result);
$gcode = $row['gcode'];
// Here list it the way you want
echo $gcode.'<br>';
}
?>
you would need to create a model or simply add this field in the search model to be searched by it. i am not sure if that is what you want to accomplish, also you would want to make sure to sanitize the request and escape it before you get one of the SQL injection attacks.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
So I have a page using PHP and a MySQL query. What I'm wanting to do is create basically an "edit" page that takes data from my database and uses it to show the values in various inputs. The user can then change the data in the input which will then update the corresponding MySQL table row. However, for whatever reason the page is NOT displaying the form, but rolling over to the else statement. I can verify the $_SESSION['weaponName'] is working, because it will echo the correct thing. Any ideas on why the form will not show up for me?
edit.php
<?php
session_start();
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$weaponName = $_SESSION['weaponName'];
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
if(mysqli_num_rows($query)>=1){
while($row = mysqli_fetch_array($query)) {
$creator= $row['creator'];
$weaponCategory= $row['weaponCategory'];
$weaponSubCategory= $row['weaponSubCategory'];
$costAmount= $row['costAmount'];
$costType= $row['costType'];
$damageS= $row['damageS'];
$damageM= $row['damageM'];
$critical= $row['critical'];
$rangeIncrement= $row['rangeIncrement'];
$weight= $row['weight'];
$weaponType= $row['weaponType'];
$masterwork= $row['masterwork'];
$attributes= $row['attributes'];
$specialAbilities= $row['specialAbilities'];
$additionalInfo= $row['additionalInfo'];
}
?>
<form action="weaponEditUpdate.php" method="post">
<input type="hidden" name="weaponName" value="<?php echo $weaponName;?>">
Weapon Name: <input type="text" name="weaponName" value="<?php echo $weaponName;?>">
<br>
Weapon Category: <select name="weaponCategory">
<?php while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['weaponCategory'] ."'>" . $row['weaponCategory'] ."</option>";
} ?>
</select>
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
As requested by OP (from comment conversations)
Instead of
if(mysqli_num_rows($query)>=1){
use
if(mysqli_num_rows($query) >0){
You're mixing functions
mysqli_connect("localhost","username","password","db_name");
Won't work with
mysql_query("SELECT * FROM weapons limit 1");
Try
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
And then
if($query->num_rows >= 1)
change this
$query = mysql_query("SELECT * FROM weapons limit 1");
to
$query = mysqli_query("SELECT * FROM weapons limit 1");
BUT omg all your code is mysql while you connected by mysqli !! .
You connect with mysqli, which is fine. THEN, you attempt to run queries via mysql. Those are two separate extensions. You can't mix them as they won't "communicate" with one another. Stick to mysqli.
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
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
I've got a drop down select box that grabs each relevant value from an SQL database in a loop.
I'm creating a form so that when the "Submit" button is pressed it redirects to a PHP file that carries out the INSERT SQL statement. However because the select options are coming from a loop I'm unsure of how to grab the right value when its selected as it just grabs the last value gained from the loop.
I'm pretty sure that the way I have done it is the wrong way to go
<?php
echo"<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>";
echo"<option>Select...</option>";
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row5 = mysql_fetch_array($result)) {
$module = $row5[2];
echo "<option name='{$module}'>".$row5[2]."</option><br />";
}
echo"</select>";
echo "<a href='submitREQ.php?id={$module}'><img src='images/submit.jpg' height='27'></a>";
?>
Instead of using <a href you should use <input type="image" value="submit" src="images/submit.jpg" />
To grab the value after the form is submitted you should use: $ModuleTitle = $_POST['ModuleTitle']; or $_GET if the method is get.