Best way to write PHP SQL Update Statement - php

I have this PHP SQL statement:
$updateCategory = "UPDATE category
SET name=".$name.", description=".$description.",
parent=".$parent.", active=".$active."
WHERE id=".$catID."";
What is the best way to write this?
Thanks,
Chris.

I suggest you use prepared statements instead of concatenating the query string together:
$sql = 'UPDATE
category
SET
name=:name,
description=:description,
parent=:parent,
active=:active
WHERE
id=:catID';
if you are using PDO, which I strongly suggest, you would then call it like this:
$params = array(
':name' => $name,
':description' => $description,
':parent' => $parent,
':active' => $active,
':catID' => $catID
);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
You might ask, "why all this hassle?" The advantages of this approach are quite overwhelming:
You don't have to care about SQL injection, since the database driver now handles the correct transformation of the input parameters
You don't have to care about escaping special characters, but you can concentrate on what you want to achieve rather than on how to achieve it :-)

You could format it like this to make it more readable.
$updateCategory = "
UPDATE
category
SET
`name` = '" . $name . "',
`description` = '" . $description . "',
`parent` = '" . $parent . "',
`active` = '" . $active . "'
WHERE
`id` = '" . $catID . "'";

I find that concatenating queries causes me major headaches with syntax errors-- all those quotes and dots sprinked around like pepper. Here's how I would write the query:
$updateCategory = "
UPDATE category
SET catname = '$name', description = '$description',
parent = '$parent', active = '$active'
WHERE id = '$catID'";
Note that "name" is a reserved word and should not be used as a column name. Also if id is an integer, $catID doesn't need to be quoted.

You can try:
$update = "update table_name SET name = '$name', email = '$email', password = '$password', phoneno = '$phoneno' WHERE id = '$id'";

Related

Trouble specifying my tablename inside query because of dot notation

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

Properly escaping mysqli query in PHP

Uggh, I've had a few beers and I just can't seem to progress.
I'm teaching myself a bit of PHP with MySQL (just because) and this one line just has me stumped:
$user = $mysqli->query ("SELECT id FROM members WHERE username = " . $_SESSION['user_name'] . " LIMIT 1");
I'm sure it's something completely stupid but I need to have the '$_SESSION['user_name']' passed with quotes around it.
Look, I know its a stupid question, apologies in advanced but I can't even get the right Google terms to find what I'm after... sad I know!\
I've tried all combinations of slash escaping and single / double quotes... please help!
You should use prepared statements :)
$stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1");
$stmt->bind_param('s', $_SESSION['user_name']);
http://es1.php.net/manual/en/mysqli-stmt.bind-param.php
You're missing the unescaped quotes, and concatenate operators. Try this:
$user = $mysqli->query ("SELECT id FROM members WHERE username = '" . $_SESSION['user_name'] . "' LIMIT 1");
Note the '" . $_SESSION['user_name'] . "' is changed.
$user = $mysqli->query ("SELECT id FROM members WHERE username = '" . $_SESSION['user_name'] . "' LIMIT 1");
As everybody stated before, the following would be a working (but not perfect!) query:
$user = $mysqli->query("SELECT `id` FROM `members` WHERE `username` = '" . $_SESSION['user_name'] . "' LIMIT 1");
But please note: Inserting strings in SQL queries this way is a security risk, since $_SESSION['user_name'] may contain quotes itself, so that somebody attacking your site could execute arbitrary SQL statements! (Search for SQL Injection if you want to get more information on this.)
Using prepared statements as suggested by naoxink is a safer way, but I just want to mention another safe way to insert strings into SQL queries: Use the mysqli::real_escape_string() method:
$user = $mysqli->query("SELECT `id` FROM `members` WHERE `username` = '" . $mysqli->real_escape_string($_SESSION['user_name']) . "' LIMIT 1");
Use this instead
$user = $mysqli->query ("SELECT `id` FROM `embers` WHERE username = '".$_SESSION['user_name']."' LIMIT 0,1");

Can't insert into mysql Auto Increment row from PHP, but can insert manually from phpmyadmin with same statement

So my problem here is that:
I cannot insert into my auto incremented column from my php
(unless I set the insert values to: '','','','$postdate','posttime').
HOWEVER: When I used the DEBUGGED insert statement below in phpmyadmin, it ran no worries.
Therefore there is something preventing my insertion from my php code.
This is my code:
$qinsert = "INSERT INTO `post` (text,sender,text_stamp,post_date,post_time) VALUES ('$message','$sender_id','$date','$postdate','$posttime')";
$finsert = mysql_query($qinsert);
$postID = mysql_insert_id();
This is the output from a debugger:
Date: Fri, 29 Mar 2013 11:02:53 -0400
Sender: User's Name
Message:
Message Text
Attachment:
Post-Date: 2013-03-29
Post-Time: 08:02:55
Q-INSRT: INSERT INTO `post` (text,sender,text_stamp,post_date,post_time) VALUES ('Message Text','User's Name ','Fri, 29 Mar 2013 11:02:53 -0400','2013-03-29','08:02:55')
F-INST:
Post-ID:
Are you escaping the variables before putting them into the array? I"m not sure if your sample query had the text and username replaced, or that was copy-pasted verbatim. I"m going to assume the later, so look closely at your query:
[...] VALUES ('Message Text','User's Name ','Fri, [...]
The 'Users's Name' has an apostrophe in the middle of it, so it's breaking the query. Make sure you're running mysql_real_escape_string($variable) on each variable before inserting it into your query.
$message_text = mysql_real_escape_string($_POST['message_text']);
$user_name = mysql_real_escape_string($_POST['user_name']);
$query = "INSERT INTO table (text, username) values ('$message_text', '$user_name')";
mysql_query($query);
You need to escape your strings, User's Name has a single quote in it. You also shouldn't use mysql_ functions, they're deprecated. But if you insist, use mysql_real_escape_string(), so something like:
$qinsert = "INSERT INTO `post` (text,sender,text_stamp,post_date,post_time) VALUES ('" . mysql_real_escape_string($message) . "','" . mysql_real_escape_string($sender_id). " ','$date','$postdate','$posttime')";
You should probably escape all strings, not just message and sender.
Ideally, you should use PDO instead, like this:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare(
"INSERT INTO post (text,sender,text_stamp,post_date,post_time) VALUES " .
"(:message, :sender_id, :date, :postdate, :posttime)"
);
$sth->execute(array(
':message' => $message,
':sender_id' => $sender_id,
':date' => $date,
':postdate' => $postdate,
':posttime' => $posttime
));
This did the trick:
require '../connect.php';
$email = file_get_contents('php://stdin');
preg_match_all("/(.*):\s(.*)\n/i", $email, $matches);
$message = $matches[1][18];
$message = str_replace('<HTML><HEAD></HEAD><BODY style="background-color:#ffffff">', '',$message);
$message = explode('<',$message);
$message = $message[0];
$sender = $matches[2][2];
$sender = explode('<',$sender);
$sender_id = $sender[0];
mysql_query("INSERT INTO `post` (`text`,`sender`,`text_stamp`,`post_date`,`post_time`) VALUES ('" . mysql_real_escape_string($message) . "','" . mysql_real_escape_string($sender_id) . "','" . mysql_real_escape_string($textdate) . "','$postdate','$posttime')") or die(mysql_error() . "<--There was error processing the query");

Textareas with dynamically-assigned name throws my code

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());

Odd Mysql issue on insert

Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.
Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}
What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.
Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));
In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()
in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.

Categories