Textareas with dynamically-assigned name throws my code - php

I have a number of textareas, each with a unique assigned name (name="adcode$ID", for example). When I try to pass those names to the code below, it doesn't work because of the dynamic part.
if (isset($_POST['editadapp'])) { // Edit AD
$newadcode = mysql_real_escape_string($_POST['.adcode$ID.']);
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
$updatead = mysql_query($doedit) or die(mysql_error());
header("Location: " . $_SERVER['PHP_SELF']);
How can I resolve this?

There is so much wrong with this that it's frightening.
Firstly,
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
That code snippet is wrong on many levels.
The sql syntax is wrong
The sql is formatted with strings from user input (see parameterization of queries here
or die() should not be used here, you're creating a string
Ideally you should have code like:
$dbh = new PDO('connectionstring to connect to your database');
$sql = 'update ads set adcode = ? where ads_id = ?';
$sth = $dbh->prepare($sql);
$sth->execute(array($_POST['adcode' . $ID], $ID));
Other topics:
Are Paramerterized queries necessary in pdo?
prepared queries with pdo
Preventing sql injection in php

You seem to be attempting string concatenation. Here's how to do that correctly:
$newadcode = mysql_real_escape_string($_POST['adcode' . $ID]);
The following line should simply create a string containing your SQL query; you don't execute it until the next line, there is no function call so the or die is out of place. You also mix concatenation with interpolation (variable names within a double quoted string) which is fine but probably not helping you understand your syntax issues, so let's be consistent:
$doedit = "UPDATE ads SET adcode = '" . $newadcode . "' WHERE ads_ID = " . $ID;

you should use array like adcode[<?php echo $ID;?>] at your page where the text area is and a hidden field name=adID[$ID]. At the page where the query executes
$adID = $_POST['adID'];
$newadcode = mysql_real_escape_string($_POST['adcode']);
$N = count($adID);
for($i=0;$N<$i;$i++){
$doedit = mysql_query("UPDATE ads SET adcode = '$newadcode[$i]' WHERE ads_ID=$adID[$i];") or die(mysql_error());

Related

Basic SQL Update statement not working in PHP

I'm working on a simple, small project for a class - a mock-database (built using phpMyAdmin) with an accompanying web application for user input, to allow for searching/appending/updating said database. Searching and Appending is working perfectly, but updating is giving me grief.
I have error messages set to display to help in the debugging process, and although they've popped up for previous issues in this project, they haven't shown up for this particular problem.
My code looks like this:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = '.$updateInformation.'
WHERE 700NUMBER = '.$updateCriteria.';";
(I tried echoing $sth right here, nothing displayed!)
$sth = $db->prepare($sth);
$sth->execute();
$updateInformation and $updateCriteria are both being pulled from an HTML form's text boxes successfully. (I'll enter Drew and 700123456 into the form as test data.) I tested that $updateInformation and $updateCriteria ARE in fact being successfully captured using this statement:
echo $updateInformation . ", " . $updateCriteria
Which yields the following output:
Drew, 700123456
I'll enter the following query into phpMyAdmin to test it first.
UPDATE adjunct_number
SET FIRSTNAME = 'DREW'
WHERE 700NUMBER = 700482306
It always works in phpMyAdmin, as expected, 100% of the time... however, the exact same update command never works when I send it through via PHP, which confusions me greatly. The only thing I can think of is an overlooked PHP typo in my SQl statement, but at this point in time I've been staring at it for so long that I could use a fresh set of eyes! Why is it that when I tried to echo $sth, no sql statement was displayed? Any insight from this wonderful community would be greatly appreciated.
You need to learn basic PHP strings:
$sth = "UPDATE adjunct_number
^---start of PHP string
SET FIRSTNAME = '.$updateInformation.'
WHERE 700NUMBER = '.$updateCriteria.';";
^---end of PHP string
That means your query is doing ... SET FIRSTNAME = '.foo.' ..., with the . embedded literally within the query. That means your where clause will never match any records.
Since you're using " for the quotes, you don't NEED to use the . at all:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = '$updateInformation'
WHERE 700NUMBER = '$updateCriteria';";
or you should properly exit the string first:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = '" . $updateInformation . "'
WHERE 700NUMBER = '" . $updateCriteria . "';";
No need of ; in your query. You are not in interactive session
You are subject to SQL injection.
No need of quote with parameterized query.
Here's a suggestion how you you could do it.
$query = "UPDATE adjunct_number SET FIRSTNAME = ? WHERE 700NUMBER = ?";
$sth = $db->prepare($query);
$sth->execute( array( $updateInformation, $updateCriteria ) );
You have mixed single and double quotes. Update it to the following:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = ".$updateInformation."
WHERE 700NUMBER = ".$updateCriteria.";
May be you can try using the symbol (" ` ")backtick for column names and tables
UPDATE `adjunct_number`
SET `FIRSTNAME` = 'DREW'
WHERE `700NUMBER` = 700482306

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

Am I using mysql_real_escape_string right?

Is this the right way to use mysql_real_escape_string? I was using $GET but a friend told me to make it safer with real_escape_string:
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = $id") or die("err0r");
if(!$result) mysql_real_escape_string($id); {
No, you normally use mysql_real_escape_string to prepare variables for use in a query, but in your case:
you already use intval;
you use it in the wrong place.
You don't need it in your example.
No. That is entirely wrong, and I can't quite understand what you're intending the call to do.
The purpose of mysql_real_escape_string is to avoid SQL injection, which is one of the biggest security risks in a website. It stops your users giving input that manipulates the SQL in evil ways. For instance:
$sql = "SELECT FROM users WHERE username = '" . $_GET['username'] . "'";
If I put lonesomeday' or 'a' = 'a into $_GET['username'], your query becomes
SELECT FROM users WHERE username = 'lonesomeday' or 'a' = 'a'
and obviously arbitrary SQL could then be executed. mysql_real_escape_string escapes unsafe characters (such as ' in that example), so that they can't be used in this way.
$sql = "SELECT FROM users WHERE username = '" . mysql_real_escape_string($_GET['username']) . "'";
// SELECT FROM users WHERE username = 'lonesomeday\' or \'a\' = \'a'
The quotes are now escaped. so the query can't be manipulated into doing evil things.
With all that said, in this case, intval does all you need. It also ensures that nothing that is not an integer can be in $id, so your code is safe here from SQL injection.
NO, you need to escape before quering
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = '" . mysql_real_escape_string($id) . "'") or die("err0r");
if(!$result) {
}
Use:
$query = sprintf("SELECT *
FROM products
WHERE id = %d",
intval($_GET['id']));
$result = mysql_query($query) or die("err0r");
You use mysql_real_escape_string before the value is used in the query, otherwise you're not handling the SQL injection attack.
you want to escape it before you stick it in a query (Before it interacts with DB so you don't get injections).
// check if your $_GET is not empty otherwise you
// will run into "undefined variable"
if(!empty($_GET['id'])){
$id = intval($_GET['id']);
// to simplify you can escape here,
// or to be a bit more complex, you can escape in the query line.
$id = mysql_real_escape_string($id);
$result = mysql_query("SELECT *
FROM products
WHERE id = '$id'") or die("err0r");
}
else
print 'No ID';

a very simple query is not working PHP

i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S
here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!
<?php
$email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];
$connection = mysql_connect('localhost','root','') ;
$db_selected = mysql_select_db("lab5" , $connection) ;
$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
while($row=mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($connection);
?>
You use single quotes in the query variable. Single quotes does not substitute variables - so it looks for literal string $email not the variable email. Either use double quotes or even better use something like PDO which would do the work for you.
You should also sanitize your inputs from SQL/XSS vulnerabilities.
The basic debugging steps are 1. adding
if (!$result) echo "Error: ".mysql_error();
to see any errors from the SQL query and 2. outputting
echo "Query: $query";
to see what the variables contain. One of these will point you to the problem.
Also, your query is vulnerable to SQL injection. You should add a
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );
after fetching the values from the POST array.
Your error probably resides in the fact that you don’t escape your parameters.
While you are at it, use MySQLi or PDO (maybe even some prepared statements)
Someone mentioned your use of single-quotes, that’s the real error, my bad.
But my advice still stands. Having used prepared statements, you wouldn’t have fell for that mistake
try
$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;
or
$query = "select * From user where email='$email' and password='$password'" ;
Try this instead:
$query = "select * From user where email='" . $email . "' and password='" . $password . "';
Then immediately change that to this instead:
$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';
Try
$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";
You've confused the single and double quotes
You have:
$query = 'select * From user where email="$email" and password="$password" ' ;
You want:
$query = "select * From user where email='$email' and password='$password' " ;
Single quotes evaluate to whats literally inside. Double quotes will parse for variables inside. Theres also a curly brace {$variable} syntax you can use.
Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well. At the very least use mysql_real_escape on parameters that come from user input.
the problem is the way you are quoting the variables. Suppose that $email= 'some#gmail.com' and $password= 'securenot'.
what we want is the final interpreted string to be the following
select * from user where email='some#gmail.com' and password='securenot'
to achieve this we simply replace the some#gmail.com for $email and securenot for $password and get the following:
select * from user where email='$email' and password='$password'.
and then in php code ...
$query = "select * from user where email='$email' and password='$password'";
hope that is of some help
mysql_fetch_assoc() for associative array. You cannot use normal array as assoc array.
while($row=mysql_fetch_assoc($result))
{
echo $row['name'];
}

Updating SQL database using PHP

I am trying to make a password retrieval system on my site, and I am having problems updating the password reset field in my database. I have tried everything, but nothing seems to work.
This is my code so far:
$passwordreset = md5(mt_rand()) . md5(mt_rand()) . md5(mt_rand());
$con = mysql_connect("localhost","XXX","XXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
mysql_query("UPDATE members SET passwordreset = $passwordreset WHERE id = $id");
When I try to insert the data I get the error:
Error: Query was empty
Any help would be appreciated,
Thanks.
Not sure it's the only problem, but I'm guessing your passwordreset field is a string, in the database -- to store a concatenation of several md5, which are strings, it has to.
So, there should be quotes arround the value you put in this field, in the SQL query :
mysql_query("UPDATE members SET passwordreset = '$passwordreset' WHERE id = $id");
And, in a general case, you should escape your string values with mysql_real_escape_string :
mysql_query("UPDATE members SET passwordreset = '"
. mysql_real_escape_string($passwordreset)
. "' WHERE id = $id");
It won't change anything here, as there is no quote in a md5... But it's a good practice to always do it, to never find yourself in a situation where it was necessary and you didn't do it.
I am not sure, if you get an empty query error for this, but you need ticks around the values:
mysql_query("UPDATE members SET passwordreset = '$passwordreset' WHERE id = '$id'");
I guess the backticks around the names of the columns are missing, try:
mysql_query("UPDATE members SET `passwordreset` = '$passwordreset' WHERE `id` = '$id'");
Are the two line breaks after $passwordreset intentional? Can you try removing them?

Categories