UPDATED:[MySQL won't update in Where condition PHP] - php

I just updated this question.
I can't seem to update my database whenever I am putting variable $ecode on my WHERE condition. But when I echo this variable it always echoes its right value.
<?php
require 'sqlicon.php';
$q=$_GET['q'];
$ecode= $_GET['ecode'];
echo"".$ecode;
$result=$db->query("UPDATE offset_form SET Approved='".$q."' WHERE Employee_Code='".$ecode."'");
?>
this is the content of sqlicon.php:
<?php
$db=new mysqli('localhost','root','',dbuser'); //localhost,username,password, dbname
?>
This is where I am getting the date for $q and $ecode: Sorry if it haven't been in mysqli yet.
testingjava.php:
<html>
<title> Offset Requests </title>
<head><link rel="stylesheet" type="text/css" href="up.css"/></head>
<script>
function Approval() {
var name;
name=document.getElementById('ename').textContent;
if(document.form1.approval[0].checked true) {
alert(name);
window.location.href = "sqli.php?q=Yes" + "&ecode=" + name;
}
}
</script>
<body>
<form id="form1" name="form1" method="post" action="testingjava.php">
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("dbuser",$conn);
$query=mysql_query("Select * from offset_form where Approved=''");
while($fetch=mysql_fetch_array($query)) {
$ecode=$fetch['Employee_Code'];
//$_SESSION['ecode']=$ecode;
$ename=$fetch['Employee_Name'];
$epos=$fetch['Employee_Position'];
$edpt=$fetch['Employee_Department'];
$dleave=$fetch['Date_Leave'];
$dreturn=$fetch['Date_Return'];
$reason=$fetch['Offset_Reason'];
echo "".$ecode ."".$ename." ".$epos." ".$edpt." ".$dleave." ".$dreturn." ".$reason;
echo "<input type='radio' name='approval' onChange='Approval()'>Yes";
echo "<input type='radio' name='approval'>No";
echo "<input type='text' name='remarks' size='30'>";
echo"<hr id='br'></hr>";
echo"<input type='submit' value='Submit' name='send' onClick='Approval()'>";
}
?>
</form>
</body>
</html>
I am only testing to manipulate my database when I triggered a radio button.

1) you should be using mysql_real_escape_string($_GET[]) or someone with inject a mysql command into you system like DROP TABLE which will be the end of your database.
2)secondly I would move over to using PHP PDO it is more secure and it is faster (by a long way).
3) change your scond to last line from
mysql_query($sql,$conn);
to
mysql_query($sql,$conn) or die(mysql_error()." _____is the string correct? ".$sql);
then is should echo out any errors, if you post the echoed error we can probably fix it
having looked at it I am guessing the problem is you have missed the .. around the $q, so the $sql contains the string "$q" rather than the string assigned to the variable $q
try this
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");

try this way..
$sql=("update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
always try to echo your query and see what's going wrong with your query..

if password is set to your dbms the provide the third param passwrod
$conn = mysql_connect("localhost","root","<passwrod>");
or you can leave it blank if passwrod is not set.
and try this
$sql="update offset_form set Approved =$q where Employee_Code=$ecode";
or
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'";
note: double quotes will parse the php variable ,
most probably there is problem in the manner of quotes you are using.

are you should your query is what you want?
One thing that is confusing is the fact that you have this commented out:
"INSERT INTO offset_form (Approved) VALUES ('".$ecode."')"
And then you have this as your update:
"UPDATE offset_form SET Approved = '$q' WHERE Employee_Code = '".$ecode."'"
The values you are using don't tally together. Surely you should have:
"UPDATE offset_form SET Approved = '$q' where Approved = '".$ecode."'"
This is because you are inserting $ecode into the column Approved, but then searching for $ecode in another column called Employee_Code. Perhaps you need to modify your insert statement instead? Either that or $ecode could be just representing two different values at different times?
quotes
The only way switching quotes will make a difference is if your embedded values contain quotes themselves. In which case using the correct escape function will sort the problem. So you are free to use either:
"UPDATE offset_form SET Approved = '$q' where Approved='$ecode'"
or:
"UPDATE offset_form SET Approved = '".$q."' where Approved = '".$ecode."'"
or:
'UPDATE offset_form SET Approved = "'.$q.'" where Approved = "'.$ecode.'"'
but not:
'UPDATE offset_form SET Approved = "$q" where Approved = "$ecode"'
either of the first three should not make a difference.
further things to do
backticks
As a rule I always write my queries escaping table and column names using backticks, just to make sure I'm not accidentally using a reserved word:
"UPDATE `offset_form` SET `Approved`='$q' WHERE `Employee_Code`='".$ecode."'"
double check your dataset
Make certain that the same query you are trying to run in PHP, works inside your dbms. This involves echoing the query out in PHP and then executing it via PHPMyAdmin, Navicat, or whatever you use to access your database outside of coding. For example, a query with hard-coded values, if this doesn't work you have a logic problem in your query or database design that has nothing to do with PHP:
"UPDATE offset_form SET Approved='13' WHERE Employee_Code='12'"
check your white space
Sometimes queries that seem they should be working are having problems because your column values contain accidental invisible white space. If so, they would only be selectable using something like:
"UPDATE offset_form SET Approved='$q' WHERE Employee_Code LIKE '%".$ecode."%'"
check user privileges
Make certain your MySQL user has the ability to perform the type of query you are attempting, this means allowing SELECT, INSERT and UPDATE queries.
disclaimer
As others have already stated, you should upgrade to non deprecated database access methods. If not, you should at least be using mysql_real_escape_string to better protect against malicious intent.

Please debug the value of $q and try to run this code:
session_start();
$q=$_GET['q'];
$ecode=$_GET['ecode'];
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("asiantech",$conn);
echo"".$ecode;
echo"<br>".$q;
$sql="update offset_form set Approved ='".mysql_real_escape_string($q)."' where Employee_Code='".$ecode."'";
//$sql = "INSERT INTO offset_form (Approved) VALUES ('".$ecode."')";
mysql_query($sql,$conn);

Related

Get ID from PHP URL and use in a query

I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)

Incomplete data displayed from query

I am trying to make an update form using PHP, getting my data from MySQL 5. I have the fields set as a TINYTEXT type. My problem is when I attempt to display a field in my form for editing, the display stops at the first space. For example: my database my have "John Doe" in one field, but when I attempt to display that field I only see "John". Here is a portion of my code:
$id =mysql_real_escape_string ($_GET['id']);
if(isset($_POST['update'])) {
$UpdateQuery = "UPDATE members SET business_name='$_POST[business_name]', phone='$_POST[phone]', fax='$_POST[fax]', address1='$_POST[address1]', address2='$_POST[address2]', city='$_POST[city]', state='$_POST[state]', zip='$_POST[zip]', website='$_POST[website]', contact='$_POST[contact]', email='$_POST[email]', update_flag='$_POST[update_flag]', WHERE id='$id'";
mysql_query($UpdateQuery, $con);
}
$sql = "SELECT * FROM members WHERE id = $id";
$my_Data = mysql_query($sql,$con);
while($record = mysql_fetch_array($my_Data)) {
?>
<form action=listingupdate.php method=post>
<tr><input type=text name=business_name value=<?=$record['business_name']?> ></tr></br>
<tr><input type=text name=phone value=<?=$record['phone']?> > </tr></br>
<tr><input type=text name=fax value=<?=$record['fax']?> > </tr></br>
I have been googling several different ways, but I have not found what I am doing wrong. Would someone be so kind as to show my what I need to do to get all of the data in a field to display in my form?
Well a few things.. You should be using mysqli, not mysql since it is deprecated. Also you're calling mysql_real_escape_string on the id, but none of the other data so your script is wide open to SQL injection attacks. It looks like your code will fail if any of the posted data contains apostrophes. I'm not sure how you're planning to use GET and POST at the same time since your form, when submitted doesn't submit a GET value. With all that said, you should check the database to see if names are getting truncated in there, or if it's a client side issue.

No errors, sql is right, table doesn't update

I'm trying to update my database via a simple form and for some reason, the table doesn't update. I tried the sql query inside phpmyadmin and it seemed to work fine.
<?php
include("_/inc/session_handler.php");
include("_/inc/dbcon.php");
$uplform = "";
if(isset($_POST['insert'])){
$post=$_POST['wish'];
$succes="";
$succes .="<h1>SUCCES</h1>";
$insert_wish_sql="INSERT INTO wishlist(wish_id, wish, datetime)VALUES (null, '$post', CURDATE())";//insert new post
echo $succes;
}
//The form
$uplform .="<form action=\"\"method=\"post\">";
$uplform .="<input type='text' name='wish' placeholder='wish'/>";
$uplform .="<input type=\"submit\" name=\"insert\" value=\"Upload\" />";
$uplform .="</form>";
?>
i even get the succes message, but nothing happens in the table. what am i missing?
UPDATE:
I just went fully retarded. i forgot to add
$link = mysql_connect($host, $login, $pw);
mysql_select_db($database);
so i was basically not connected to the database 8-|.
Thanx a lot!
I miss your connection to a database server ( I guess its' that include) and finally if a connection exits, you need to send/execute your query.
The API's: PDO or mysqli is good for it.
or to test stuff, with the mysql API ( but I would not recommend it to use it live)
http://ch1.php.net/manual/en/book.mysql.php
There may be one problem looking at your code is that it is not executed. SO execute it like this
$res = mysqli_query($conn, $insert_wish_sql);
But the bigger concern is your sql itself as you are passing null as the value for id. Is your id is not primary or auto increment. If it is then it will fail always.

Display usernames at random

I’m trying to create a script for a user to enter in their username, and then have other logged in usernames randomly show, in a chatroulette fashion.
So, you will enter in your name and hit submit, then your name will be stored in a database and someone else’s name will be pulled out at random and shown. Then the user can hit a next button to see another random user name. When the user closes the page, their name will be unloaded from the system.
What I have tried is creating a simple post submission form which will return you to the same page logged in with your name, and it inserts your name into a mysql database. That worked.
Then I added some PHP code to detect that the name variable has been set and to find a random username in the database by finding the amount of users in the database and using a random integer to pick one out. I’m pretty sure it worked, however I was unable to get the user name to show with echo "$name";.
Then I tried adding an automatic logout by using:
<body onUnload=<?php session_destroy();?>>
That didn’t work. I didn’t get around to creating a next button because I was having a few problems, because I figured out that the logout wouldn’t work because I would be dropping rows from the database that wouldn’t be filled in again as new rows were added to the SQL database with an auto increment function causing blank pages to be shown.
Here is my code:
<html>
<head>
<title>random name</title>
</head>
<body>
<center>
<h1>random name</h1>
<h5>By DingleNutZ</h5>
</center>
<?php
if (!isset($_POST['name'])){
echo "<form action=\"index.php\" method=\"POST\" name=\"form\"><center><h4>name:</h4><input name=\"name\" id=\"name\" type=\"text\"/><br/>
<input type=\"submit\" name=\"submit\" value=\"Play!\"/></center></form>";
}else{
$name = $_POST['name'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="ftr"; // Database name
$tbl_name="players"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// To protect MySQL injection (more detail about MySQL injection)
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
session_register("name");
session_start();
if(session_is_registered(name)){
$players=mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand=rand(1,$players);
$callee=mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
echo "Logout";
if (isset($playing)){
if ($playing == 1){
$drop_name=mysql_query("DELETE FROM $tbl_name WHERE name=$name");
}}
}
}
echo "show random name here";
}
?>
</body>
</html>
There is a variable in there called $playing which was an attempt at a logout system.
I would be very grateful for any answers. Many thanks in advance.
as i didnt make it obvious (sorry guys) i need to fix my main problem which is being able to show a random user without ever showing a blank page due to the rows being dropped from the database. it is essential that usernames are removed from the system for privacy
You have a few issues in your code, not all are errors as such, some code is unneeded, other code is potentially dangerous.
$name = stripslashes($name); <<-- delete this line.
$name = mysql_real_escape_string($name); <<-- this is all you need.
mysql_real_escape_string() is all you need. No other escaping is need to protect against SQL-injection.
A few caveats apply, which I will discuss below.
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
Select * is an anti-pattern, never use it in production code. Explicitly select the fields you need.
You are using dynamic tablenames, I fail to see the need for this and it's also a dangerous SQL-injection hole.
Never use it but if you must, see this question how to secure your code: How to prevent SQL injection with dynamic tablenames?
You do the query, but you don't test if it succeeds, put a test in there:
$sql = "SELECT id FROM users WHERE name='$name' ";
$result = mysql_query($sql);
if ($result)
{
$row = mysql_fetch_array($result);
$user_id = $row['id'];
}
else { do stuff to handle failure }
You are trying to get data out of the database, but this is not the way to do it:
$players = mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand = rand(1,$players);
$callee = mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
But I see a few issues:
Please stop using dyname tablenames, it is a really bad idea.
The return value of mysql_query is a query_handle, not the actual data you're quering.
I would suggest escaping all values, whether from outside or inside your code; I know this is paranoid, but that way, if you code design changes, you cannot forget to put the escaping in.
Never ever ever echo unsanitized data in an echo statement.
If you echo a $var, always sanitize it using htmlentities. If you don't XSS security holes will be your fate.
See: What are the best practices for avoiding xss attacks in a PHP site
rewrite the code to:
$result = mysql_query("SELECT MAX (id) as player_id FROM users");
$row = mysql_fetch_array($result);
$max_player = $row['player_id'];
$chooserand = mysql_real_escape_string(rand(1,$max_player));
//not needed here, but if you change the code, the escaping will already be there.
//this also makes code review trivial for people who are not hep to SQL-injection.
$result = mysql_query("SELECT name FROM users WHERE id = '$chooserand' ");
$row = mysql_fetch_array($result);
$callee = $row['name'];
echo "callee is ".htmlentities($callee);
Finally you are deleting rows from a table, this looks like a very strange thing to do, but it is possible, however your code does not work:
$drop_name = mysql_query("DELETE FROM $tbl_name WHERE name=$name");
As discussed mysql_query does not return values.
On top of that only a SELECT query returns a resultset, a DELETE just returns success or failure.
All $vars must be quoted, this is a syntax error at best and an SQL-injection hole at worst.
Technically integers don't have to be, but I insist on quoting and escaping them anyway, because it makes your code consistent and thus much easier to check for correctness and it elimiates the chance of making errors when changing code
Rewrite the code to:
$drop_name = $name;
$result = mysql_query("DELETE FROM users WHERE id = '$user_id' ");
//user_id (see above) is unique, username might not be.
//better to use unique id's when deleting.
$deleted_row_count = mysql_affected_rows($result);
if ($deleted_row_count == 0)
{
echo "no user deleted";
} else {
echo "user: ".htmlentities($drop_name)." has been deleted";
}

Using a form to update data in MySQL

Having trouble getting my form to UPDATE records in my database even after searching the web and viewing the other answers on stack-overflow.
Here is my current NON functioning code:
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
session_start();
$tablename = $_SESSION['MM_Username'];
$amount=$_POST['amount'];
$UpdateQuery = "UPDATE '" . $tablename . "' SET stock = '" . $amount . "' WHERE status = 1";
mysql_query($UpdateQuery);
}
The table i want to update has the same name as the SESSION variable MM_Username. I have a form with a textbox named amount and a Submit button that when clicked, should trigger the above code. If you need to know anything else let me know. Thanks in advance!
You're using the wrong quotes around your table name. Also, your query is open to SQL injection. Consider using PDO and bind parameters.
$UpdateQuery = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1',
$tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
Have MySQL tell you what the problem is. Change the last line of your code to this:
if (!mysql_query($UpdateQuery)) {
echo mysql_error();
}
Print out if you are having your tablename in your session variable.
print $_SESSION['MM_Username'];
Also print out the $UpdateQuery and see how the mysql query is formed. Copy that query & try running it manually in mysql to see if the query is ok.
ADVISE: I see that you have used $_POST. This is fine, but I advise you to use $_REQUEST. This var in PHP has all $_POST & $_GET content. Sometimes one forgets to change the $_POST to $_GET or vice versa & ends up wasting his time, debuggin.
if (!mysql_query($UpdateQuery)) {
echo mysql_error()
}

Categories