mySQL WHERE clause issue in PHP - php

I have created a page where it lets users to edit their information which is stored in the database. However i can't get the WHERE clause to work it just keeps coming up with entry not found. Any help would be great thanks.!
<?php
mysql_connect('localhost', 'root', 'password') or die(mysql_error());
mysql_select_db("peopletank") or die(mysql_error());
$query = mysql_query("SELECT * FROM users WHERE id='$id'")
or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$firstname= $row['firstname'];
$secondname= $row['secondname'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?php echo $id;?>">
Value1: <input type="text" name="value1" value="<?php echo $firstname;?>">
<br>
Value2: <input type="text" name="value2" value="<?php echo $secondname?>">
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>

Try this :
$query = mysql_query("SELECT * FROM users WHERE id='".$id."'");
Make sure your $id is populated correctly. Try checking the value first if the query still didn't showed up like this :
echo 'The id is : '.$id;
$query = mysql_query("SELECT * FROM users WHERE id='".$id."'");
If the $id is populated correctly but still return no result then run the query manually in your mysql database, probably there is no result for specified $id
And while populating data, no need to fetch $id while you just have same $id ini this query.
while($row = mysql_fetch_array($query)) {
$id = $row['id']; /* << Remove this */
$firstname= $row['firstname'];
$secondname= $row['secondname'];
}

I aint 100% sure if its one of these things:
1) Try ending the statements with ;
2) Numbers dont have to be between ''
3) Try putting names of columns between ``
4) use LIMIT 1 where you can (makes things faster but not important)
5) Always try to use a selecter (faster)
<?
if ( $query = mysql_query("SELECT `firstname`,`secondname` FROM `users` WHERE (`id` = $id) LIMIT 1;"))
{
if ($r = mysql_fetch_assoc($query))
{
$firstname = $r['firstname'];
$secondname = $r['secondname'];
}
}
?>

Related

How to display mysql data from php in html form.(NOT TABLE)

I have been looking for a solution for this for a while but they all pertain to html tables. I have a simple form and have manually added values into the database using phpMyAdmin. I have a drop down menu at the top and whenever the admin selects a particular name from the drop down menu and presses the 'Display the fields' button, I want all the respective fields to be filled in with the values after which the admin can make changes onto any particular field and update. How can I get those values to be filled? I have tried multiple codes but keep getting errors such as undefined index, undefined variable etc. Can someone help me with that?
<!doctype html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dealer_track";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed". $conn->connect_error);
}
if(isset($_POST['id1'])){
$sql = "SELECT * FROM tbl_dealer_info ";
$sql .= "WHERE $account_name = 'account_name' ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
?>
<html>
<head>
<title>iMobile </title>
</head>
<body bgcolor = "#D6DFE3">
<center><b><h2>Please enter the following information: </h2></b></center>
<form action = "dealer_track.php" method = "post">
<strong><center> <u>Fields marked with an asterisk(*) are required.</u><br><br>
Name of the dealer:* // This is where the admin selects the user they would like to update
<?php
$sql = "SELECT account_name FROM tbl_dealer_info ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'account_name' id = 'id'>";
echo "<option value = ''>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['account_name'] . "'>" . $row['account_name'] . "</option>";
}
echo "</select>";
?>
<br><br>
<input type = submit id = "id1" name = "id1" value = "Display the fields" /><br>
</center>
<hr>
<br><br>
</form>
<form action = "dealer_track.php" method = "post">
Email:*<br>
<input type = "email" name = "email" id = "id3" value = "<?php echo $row['email']?>" Required /><br><br>
RSM:*<br>
<?php
$sql = "SELECT rsm_val FROM tbl_rsm_drop_down ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'rsm_val'>";
echo "<option value = ''></option>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['rsm_val'] . "'>" . $row['rsm_val'] . "</option>";
}
echo "</select>";
?>
<br><br>
**// My radio buttons aren't getting checked though**
iPhone Boost Approved:
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="Yes")?> value = "Yes" />Yes
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="No")?> value = "No" />No<br><br>
</form>
<?php
}} // While loop and if loop at the start
?>
</body>
</html>
I'm taking a wild guess here, so I'm assuming you want to select a user from a dropdown (That could be a bad idea if many people are in said database), but you would want to make a simple HTML form and name it somethign you will remember. Under the form put this?
<?php
if(isset($_POST['formnamehere'])) {
$sql = "SELECT * FROM (table name) WHERE accountname=" . $accountname;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row['accountname'];
//put other things here, etc.
}
?>
Granted this code is not meant to be used exactly. but to give you a general idea.
You code is a bit messy but here is what you need to do generally.
First query for the unique record:
$sqlQuery = "SELECT id, firstname, lastname FROM Table Where id = '$id'";
Then run the query:
$result = $connection->query($sqlQuery ); //nb: $connection is your connection variable
Then check if any result found:
if ($result->num_rows > 0) { ........ }
If any records found then put the fetched data in variables like this
while($row = $result->fetch_assoc()) {
$firstname = $row["firstname"];
$lastname = $row["lastname"];
//and so on....
}
// You can display these variables any how you want in here, eg:
echo "<h2>$firstname</h2>";
or
<input type="text" id="firstname" name="firstname" value="<?php echo $firstname ?>" />
//nb: you must close the php tag before using html and re open it after
if "if ($result->num_rows > 0) {...} is false, just use an else {...} to display a message
You can run a query with your active connection to fetch your respective information from the table you want, along with a search clause for where the name is equal to a given value.
Query:
$result = mysqli_query($con, "SELECT `data` FROM `table` WHERE `name` = '$name';");
You can then display your data on your front end by outputting the result.
<?php
if($row = mysqli_fetch_array($result)) {
echo $row["data"];
}
?>

Deleting from table using drop down list

I have a problem with deleting from mySQL table. I'm using drop down list to select which name (id) I need to delete. Please help.
<h1>Delete product</h1>
<form method="post" action = "Delete.php">
<div class="Delete">
<select>
<?php
require('connect.php');
$query = mysql_query("SELECT name FROM `products`");
$id = mysql_query("SELECT id FROM `products`");
while($row=mysql_fetch_array($query)){
echo "<option value='". $row = $_POST['id']."'>".$row['name'].'</option>';
}
?>
</select>
<input type="submit" name="" value="Delete">
</form>
</div>
And this is script. It makes error on line 10 - if(isset($_POST['id'])){
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
require('connect.php');
$id = mysql_query("SELECT id FROM `products`");
if(isset($_POST['id'])){
$id = mysql_real_escape_string($_POST['id']);
$query2 = "DELETE FROM `products` WHERE id = '$id'";
$result=mysql_query($query2);
if($result){
header("Location: tools.php");
exit;
}
else{
echo"ERROR";
}
}
else{
echo"Bad ID";
}
}
?>
Try something like this
//Give select a name so delete.php can hook into it
<select name="product_id">
<?php
require('connect.php');
//Merge your 2 queries into one
$query = mysql_query("SELECT id, name FROM products");
//Fix value fetching in your while loop
while($row=mysql_fetch_array($query)){
echo "<option value='". $row['id']."'>".$row['name'].'</option>';
}
?>
</select>
Then in your submit script
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
require('connect.php');
//Look for select name
if(isset($_POST['product_id'])){
//Get ID from select value
$id = mysql_real_escape_string($_POST['product_id']);
$query = "DELETE FROM products WHERE id = '$id'";
$result = mysql_query($query);
if($result){
header("Location: tools.php");
exit;
}
else{
echo"ERROR";
}
}
else{
echo"Bad ID";
}
}
?>
I havnt tested this but with minor tweaking if any, it should now work for you.
What i have done
Given your a name so it can be picked up by delete.php
Merged your product name, id fetch queries into 1 query
Killed off that $row = $_POST['id'] statement :S
In delete.php checked for the select name (given in bullet 2)
Clean up id depeneding on selected value
Ran delete query
Hope this helps

pulling database and update database - php

I have rows showing products and their stockings.
I can pull out records from the database but somehow I am stuck at the editing part. When I click on edit I don't know how to pass the id so I can use the id to select what is needed to be selected in the table.
I have something like stock.php which shows all item_name and stock
<?php
$sql = "SELECT * FROM inventory";
$result = mysqli_query($mysqli,$sql);
//make sure database queries
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
if ($result->num_rows > 0) {
echo "<table><tr><td>Name</td>
<td>Stock</td>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
echo "<tr>
<td>".$row["item_name"]."</td>
<td>".$row["stock"]."</td>
<td>
<form action='edit.php' method='POST'>
<input type='hidden' name='$id' value='$id'/>
<input type='submit' name='edit' value='edit' />
</form>
</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
in my edit.php I have something like this which is giving me error because the $id is not passed
include_once "init.php";
if ($_SERVER['REQUEST_METHOD']=='POST') {
// query the table by matching up the int id
$sql = "SELECT * FROM inventory WHERE id = '$id'";
}
I want to pull out the data again in a new page and then having input box again to let users update stock # or even the product name and others if necessary.
There is an error in your input declaration. HTML items can't have names that start with special characters (like the $). You should be setting the variable-based names this way:
<input type='hidden' name='".$id."' value='".$id."'/>
Also in your edit.php, your SQL statement has a bug.
$sql = "SELECT * FROM inventory WHERE id = '$id'";
should be:
$sql = "SELECT * FROM inventory WHERE id = ".intval($id);
You need to do the following updates:
stock.php
<input type='hidden' name='id' value='$id'/>
edit.php
$sql = "SELECT * FROM inventory WHERE id = '".$_POST["id"]."'";
you are passing the current id value as the post var name, the var's name should be "id"

PHP - Mysql Query

I have a problem regarding my correct script for query..
I created a form in page1.php where the user have to input the fname, mname, and lname.
page1.php
<form action = "page2.php" method="post" target="<?php $_SERVER['PHP_SELF']?>">
First Name:<input type="text" name="fname"/>
Middle Name:<input type="text" name="mname"/>
Last Name:<input class = "type="text" name="lname"/>
<input type="submit" name="submit" value="NEXT" />
</form>
The entries are sent to page2.php to be inserted into the database. After successful process. I placed a condition after a successful insertion of the values, it automatically goes to page3.php.
page2.php
<?php
include('config.php');
if(isset($_POST['submit']))
{
$fname = ucwords(strtolower($_POST['fname']));
$lname = ucwords(strtolower($_POST['lname']));
$mname = ucwords(strtolower($_POST['mname']));
$submit=$_POST['submit'];
if(empty($fname) || empty($lname) || empty($mname))
{
echo '<b>Please fill out the form completely.</b>';
}
else
{
$dup = mysql_query("SELECT *
FROM
tbl
WHERE
fname = '$fname'
AND
lname = '$lname'
AND
mname = '$mname'
");
if(mysql_num_rows($dup) >0)
{
echo "<br/>";
echo '<b>Already Registered.</b>';
echo "<br/>";
}
else
{
$sql = mysql_query("INSERT INTO tbl(fname,lname,mname) VALUES('$fname','$lname','$mname')");
if($sql)
{
echo "<br/>";
echo "You have successfully added your new name!";
echo "<br/>";
header("Location: page3.php?fname= $fname&mname= $mname &lname= $lname");
}
else
{
echo "Error Registration";
header("Location: index.php");
}
}
}
}
?>
The values will also be carried over by the:
header("Location: page3.php?fname= $fname&mname= $mname &lname= $lname");
which is placed right after the:
$sql = mysql_query("INSERT INTO tbl(fname,lname,mname)VALUES('$fname','$lname','$mname')");
Then goes to next page.
In page3.php, in order to verify that I still have the values I used:
echo '<pre>' . print_r($_GET,true) . '</pre>';
And I still have them.
Now, in page3.php I want to call the auto_incremented ID that was created after the successful insertion of the values from page2.php.
<?php
echo '<pre>' . print_r($_GET,true) . '</pre>';
include('config.php');
$fname = $_GET['fname'];
$mname = $_GET['mname'];
$lname = $_GET['lname'];
$sql = mysql_query("SELECT * FROM tbl WHERE fname = '$fname' AND mname = '$mname' AND lname = '$lname'");
while ($row = mysql_fetch_array($sql))
{
echo $row['id'];
}
?>
Now, the problem is that their no results coming out from my query. When I try this is script:
$sql = mysql_query("SELECT * FROM tbl");
I have results showing up.
What I want to do is this, I want the conditions to be fulfilled altogether namely the fname, mname, lname. The 3 fields must be satisfied so that I can get the specified ID from the table which has those fields specifically. Its like you have the query your fullname and get the ID for you. You should insert all 3 fields in order to get the exact ID for that given name.
My problem probably lies here:
$sql = mysql_query("SELECT * FROM tbl WHERE fname = '$fname' AND mname = '$mname' AND lname = '$lname'");
while ($row = mysql_fetch_array($sql))
{
echo $row['id'];
}
It's like you to have John Rogers Smith then find out your ID from the database.
Can you help me? I dont understand why it's not working.
Tnx guys in advance.
Please check every stap you do, because the form already has an error
Last Name:<input class = "type="text" name="lname"/>
needs to be
Last Name:<input class="" type="text" name="lname"/>
and the way you do the querys is not secure, its easy to do sql injection.
Also i would suggest you to use sprintf(), example:
$s_query = sprintf("SELECT * FROM `x` WHERE `x`.`x_name` = '%s'", $x_name);
And you should go for mysqli instead of mysql.
Next time always print out every stap, use print_r() to print arrays like $_GET and $_POST
may i ask to all it may work without give error or warning
echo "Error Registration";
header("Location: index.php");

MySQL update doesn't work

I want to update 2 of my database's fields according to user input.My code is something like this:
<body>
<?php
$db_server["host"] = "localhost"; //database server
$db_server["username"] = "root"; // DB username
$db_server["password"] = "mypass"; // DB password
$db_server["database"] = "mudb";// database name
$dbc = mysql_connect($db_server["host"], $db_server["username"], $db_server["password"]);
mysql_select_db($db_server["database"], $dbc);
$user = $_COOKIE['mycookie'];
$q = "SELECT * FROM members WHERE username='$user'";
$r = mysql_query( $q,$dbc);
while ($row = mysql_fetch_array($r, MYSQLI_ASSOC)) {
echo 'username: '.$row['username'], '<br/>';
$password=$row['password'];
?>
<form method="post" id="changepasswordform" >
<input type="password" id="newpassword" name="newpassword"/>
<input type="submit" name="changepasswordbutton" >
</form>
<?php
echo 'email: '.$row['email'], '<br/>';
}
?>
<form method="post" id="changeemailform" >
<input type="text" id="newemail" name="newemail"/>
<input type="submit" value="αλλαγή" name="changeemailbutton" >
</form>
<?php
}
if (isset($_POST['changepasswordbutton'])){
$newpassword=$_POST['newpassword'];
$q2 = "UPDATE members SET password=$newpassword WHERE username='$user'";
$r2 = mysql_query($q2,$dbc);
}
if (isset($_POST['changeemailbutton'])){
$newemail=$_POST['newemail'];
$q3 = "UPDATE members SET email=$newemail WHERE username='$user'";
$r3 = #mysql_query( $q3,$dbc);
}
?>
</body>
However although my connection to my db is ok(SELECT displays results as expected) when i try to UPDATE , the values inside my db remain the same.I checked the values of $newpassword and $newemail and they do contain the user inputs each time.What am i missing here?
You're missing the '' (quotes) that supposed to surround the password field.
change:
UPDATE members SET password=$newpassword WHERE username='$user'
to:
UPDATE members SET password='{mysql_real_escape_string($password)}'
WHERE username='{mysql_real_escape_string($user)}'
IMPORTANT:
And even though it's not related, please don't use mysql_* functions - it's deprecated and vulnerable to sql-injection. Better use PDO or MySQLi.
This will do the trick and is save for sql injection (mysql_real_escape_string):
$q2 = "UPDATE members SET
password='". mysql_real_escape_string($password) ."'
WHERE username='". mysql_real_escape_string($user) ."';
But off course you shouldn't use mysql_* anymore, I'm just giving an example for your specific case.

Categories