I have just implemented mysql_real_escape_string() and now my script won't write to the DB. Everything worked fine before adding mysql_real_escape_string():
Any ideas??
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
mysql_send("INSERT INTO list
SET id = '',
name = '$name',
description = '$description',
custid = '$custid' ");
what is that mysql_send function?
what if to change it to mysql_query();
It should be easy to figure out what's going on.
Fist, instead of sending the query you're constructing to the database, echo it out (or log it), and see what you're actually sending to the database.
If that doesn't make it obvious, see what mysql_error() has to say.
mysql_real_escape_string should have a database connection passed as the second argument since it asks the database what characters need to be escaped.
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
$cleanstring = mysql_real_escape_string("my string", $connection);
A typical failure on understanding how to use certain functions...
You're just using mysql_real_escape_string on raw input data. Have you ever heard of santizing / validating input? mysql_real_escape_string does not make sense on numbers. If you've validated a variable to be a number, you don't need to escape it.
mysql_send is an alias for mysql_query right?
Use debug code, add echo mysql_error(); after mysql_send(...).
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
//If you doing Update use this code
mysql_query("UPDATE list SET id = '', name = '$name', description = '$description' WHERE custid = '$custid' ") or die(mysql_error());
//OR if you doing Insert use this code.
mysql_query("INSERT INTO list(name, description, custid) VALUES('$name', '$description', '$custid')") or die(mysql_error());
//If custid is Integer type user $custid instead of '$custid'.
If you are updating the records in the list table based on the custid use the UPDATE command OR if you are insertinf the records into list table use INSERT command.
Related
I wrote this code
if(isset($_POST['update'])) {
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
$sql=("UPDATE settings (name, meta, description) VALUES ('$webname', '$webmeta', '$webdesc')");
}
but the problem is that it doesn't update my database, and I cannot find anything wrong in the code ...
I have name "update" on submit button, and all my fields are the same as in code
That's insert! Not update!
$sql=("UPDATE `settings` SET `name` = '$webname',
`meta` = '$webmeta',
`description` = '$webdesc')
WHERE [some condition]");
And replace the [some condition] with a valid condition.
Your code is heavily vulnerable to SQL Injection.
Consider escaping the input by replacing these:
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
With:
$webname = mysql_real_escape_string($_POST['webname']);
$webmeta = mysql_real_escape_string($_POST['webmeta']);
$webdesc = mysql_real_escape_string($_POST['webdesc']);
Or something equivalent like PDO or MySQLi.
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
u need to first formulate query ans then run/ execute that
$query = "UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value";
// Perform Query
$result = mysql_query($query);
You need to run
$connection = mysql_connect($server, $serv_Username, $serv_Password);
mysql_select_db($dbase_name, $connection);
mysql_query($update_query, $connection));
I don't know if this is your problem (don't know how much you know about PHP so just saying).
Also your syntax is wrong. Should be:
UPDATE tablename SET column_name='some_value' WHERE column_name ='some_value'
note that this is diffrent from mentioned above without the thingys covering the column_name parameters.
better is to use PDO as mentioned above, mysql_ can be used "safely" on < PHP 5.5.
Try The code shown below
Just replace the field names and values with your information on your database
$editid=$_POST['editid'];
$username=callback($_POST['username']);
$password=callback($_POST['password']);
$name=callback($_POST['name']);
$age=callback($_POST['age']);
$phone=callback($_POST['phone']);
$emailaddress=callback($_POST['emailaddress']);
$gender=callback($_POST['gender']);
$description=callback($_POST['description']);
$update=update("users","username='".$username."',password='".$password."',name='".$name."',age='".$age."',phone='".$phone."',emailaddress='".$emailaddress."',gender='".$gender."',description='".$description."' ","ID='".$editid."' " );
I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.
newbie at php here, basically I wish to know how to add data to my mysql table manually using the url.
For example, say I have a table called users which has 3 fields called 'ID', 'username' and 'password'. I wish to add data to the table like this:
http://localhost/register.php?id=1#username=bob#password=123#act=register (I'm not sure if this is entirely right) but yeah something like that.
Any help on how to do this would be much appreciated!
mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database');
mysql_query("INSERT INTO table (id, username, password) VALUES ('".mysql_real_escape_string($_GET['id'])."', '".mysql_real_escape_string($_GET['username'])."', '".mysql_real_escape_string($_GET['password'])."')");
$query = "insert into users (username, password) values ('".$_GET['username']."','".$_GET['password']."'";
That would be to insert a user based on the act parameter.
Also, usually parameters on a get are split up by "&", not "#".
First of all, if you're saving large data, better to use POST, rather than GET. But if you really need to send data to the server with URL, your URL should be change as below:
You should use '&' in place of '#'
http://localhost/register.php?id=1&username=bob&password=123&act=register
In Server side, you can retrieve the data by following:
$id = mysql_real_escape_string($_GET['id']);
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$sql = mysql_query('INSERT INTO table_name (id, username, password) VALUES ('.$id.', '.$username.', '.$password.');
if(!$sql){
echo "Error " . mysql_error();
}else{
echo "Success";
}
use
$id = $_REQUEST['id'];
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$act = $_REQUEST['act'];
to get values from url
Then usual MySQL
Insert Query
refer
http://dev.mysql.com/doc/refman/5.5/en/insert.html
Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.
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?