Php Insert into adding blank entries - php

I'm trying to add new entries to an sql database using php,
i can add a new entry, but it adds 2 blank lines to the database.
The query i use is
$query = "INSERT INTO dbo.Products (Name,Id,Price) VALUES ('$NewName','$NewId','$Price')";
$result = sqlsrv_query($conn3, $query);
any ideas why it'd do that?

Try using VALUE instead of VALUES to make sure only a single entry is added.
This should limit the insertion to a single item only. It then depends if you are keen to debug the issue more thoroughly to see what was the problem.
Lastly, it never hurts to check if the variables are all properly escaped.

You can try
$sql = "INSERT INTO dbo.Products (Name,Id,Price) VALUES('%s','%d','%f')";
$result = sqlsrv_query($conn3, sprintf($sql,mysql_real_escape_string($NewName),$NewId,$Price));

Related

saving information to database from webform

$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW())";
$query = "INSERT INTO address ". "(house_number,street_name,town/city,postcode,province/county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county', NOW())";
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
So I can create a connection to my database no problem and on my previous page I can send username and password to the database but then I come to the user details page to save the information and continually getting Invalid query 2 error. The table names are correct (users & address) and all variables are spelt correctly. Does anyone have a suggestion to fix the issue or a better alternative (I mean to just point me in the right direction of the research I should be looking at if I am way off target, if I have just mispelled something or have something in the wrong place then I would appreciate the heads up, have been at this quite a while now)
This is the code from the previous page and it works fine and sends the information to the database:
$query = "INSERT INTO login ". "(username,password) ". "VALUES('$uname','$epass', NOW())";// sets up sql query
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
mysqli_close($conn); // close database connection
As far as I know all the database side of things is fine, all data types are varchar except for dob which is date (I have tried changing this to varchar to see if it fixed the problem but it didnt) and userID is int and is an autoincrement for the unique primary key. I have also tested the php file without the validation rules and still gives the same error.
Quite a few things wrong here.
First you are reassigning the variable $query; so the first insert will be getting overwritten by the second, you need to concat the variable.
Then you have 2 queries you are attempting to send at one time. However you never tell Sql you've finished your first before starting your second.
Try the following instead take note Of The semi colons ; at the end of each.
You are also putting slashes into your column names which is illegal.
Lastly, you've got more values to insert than you have columns. Remove the now() from the end.
$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email');";
$query .= "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county');";
Although this will now work, I highly recommend you do some research regarding safe practices with Sql.
Here would be a great starting point https://www.w3schools.com/php/php_mysql_prepared_statements.asp
On a side note, why are you concating your Strings? There's no need
$query = "INSERT INTO users (first_name,last_name,dob,mobile_number,landline_number,email) VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW());";
Maybe it's the fact that you are closing the connection after your first call.
try or die(mysqli_error($conn));
EDIT:
Delete passing value "NOW()".
code:
$query = "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county')";

Insert mysql error when parsing a webpage

Hi when ever I want to insert a comment into my database, I sanitize the data by using Mysql Escape String function this however inserts the following verbatim in field. I print the comment and it works fine and show me the text however when ever I sanitize it, it literally inserts the following into my db
mysql_real_escape_string(Comment)
This is my insert statement, The Id inserts correctly however the comment doesn't it just inserts the "mysql_real_escape_string(Comment)" into the field. what can be wrong?
foreach($html->find("div[class=comment]") as $content){
$comment = $content->plaintext;
$username = mysql_real_escape_string($comment);
$querytwo = "insert into Tchild(Tid,Tcomment)values('$id','$username')";
$resulttwo = $db -> Execute($querytwo);
}
If I'm reading the documentation correctly, you should make the call like this:
$db->Execute("insert into Tchild(Tid,Tcomment)values(?, ?)", array($id, $username));
That will account for proper escaping. Having unescaped values in your query string is dangerous and should be avoided whenever possible. As your database layer has support for SQL placeholders like ? you should make full use of those any time you're placing data in your query.
A call to mysql_real_escape_string will not work unless you're using mysql_query. It needs a connection to a MySQL database to function properly.
Since you're using ADODB, what you want is probably $db->qstr(). For example:
$username = $db->qstr($comment, get_magic_quotes_gpc());
See this page for more information: http://phplens.com/lens/adodb/docs-adodb.htm

What am I doing wrong with inserting?

I tried both
$query = "INSERT INTO reservation VALUES ('".$hour."','".$minute."','".$day."','".$month."','".$year."','".$name."','".$table."')";
$query = "INSERT INTO reservation VALUES ('$hour','$minute','$day','$month','$year','$name','$table')";
But none of them work, I get a blank page, and no errors in my error logs. I tried doing echo to all the variables and I got their values.
Here is the overall function:
function makeReservation($trtime,$hour,$minute,$day,$month,$year,$name,$table,&$db)
{
//$query = "INSERT INTO reservation VALUES ('".$hour."','".$minute."','".$day."','".$month."','".$year."','".$name."','".$table."')";
$query = "INSERT INTO reservation VALUES ('$hour','$minute','$day','$month','$year','$name','$table')";
$result = $db->query($query) or die(mysql_error());
}
I'll make a few suggestions. First, I'll assume that you actually know what you're doing when you say there is no error.
1) Make sure you work on the good database. You can do a SHOW TABLES query to see what tables it contains, or a SELECT * FROM reservation to see its content.
2) Right after you insert the row, do a SELECT * FROM reservation query and check if your row is there.
3) Make sure you call your function...
Then, as I said in comments, you should use the DATETIME type instead of using different columns for hours, minutes, etc. If you need to select a particular attribute, use the appropriate function (for example, SELECT HOUR(your_column))
The quotes around integers shouldn't make your query fails, but it's still better for clean code purposes to remove them if not necessary (and make sure you escape your data correctly, of course).
The php you posted looks fine.
If you're getting a blank page, it's likely that something is failing before the function calls. Maybe a parsing error?
If you're not seeing anything in the error logs, try changing your error logging settings in the php.ini.
display_errors = E_ALL
If you're on shared hosting, you can often override using .htaccess http://davidwalsh.name/php-values-htaccess

mysql_real_escape_string again if copying data?

Before I put data into my database I pass it through mysql_real_escape_string.
If I want to copy that same data into another table, do I need to pass it through mysql_real_escape_string again before I copy it?
I wrote a small script to test the issue and it looks like the answer is yes:
$db = new AQLDatabase();
$db->connect();
$title = "imran's color";
$title = mysql_real_escape_string($title);
$sql = "insert into tags (title, color) values ('".$title."','#32324')";
$db->executeSQL($sql);
$sql = "select * from tags where color = '#32324' ";
$result = $db->executeSQL($sql);
while($row= mysql_fetch_array($result))
{
$new_title = $row['title'];
}
$new_title = mysql_real_escape_string($new_title);
$sql = "insert into tags (title, color) values ('".$new_title."','DDDDD')";
$db->executeSQL($sql);
NOTE: If I remove the second mysql_real_escape_string call, then the second insert won't take place
Are doing something like this?
save mysql_real_escape_string($bla) to database
fetch $bla from database
save $bla again (in another table..)
Fetching $bla from the database will "unescape" it so it could be a harmful string again. Always escape it again when saving it.
Before I put data into my database I always make it go the Mysql_real_Escape_String thing.
You are doing right. Just keep it as is. Not database though but query it is.
The only note: only strings should be escaped using this function. It shouldn't be used with any other query parts.
do I need to make it go through the Mysql_real_Escape_String again before I copy it?
Didn't you answer your question already? Before I put [string-type] data into my [query] I always make it go the Mysql_real_Escape_String thing. Is your data going to SQL query? So, here is an answer you have already.
Well, if you are sure this data is already properly escaped, there is no need to.
mysql_real_escape_string is for 1) escaping 2) security purposes. Since it's your own data base and as long as you pass data to another database outside a potential hacker reach - you are already safe
Its already scaped, just copy it as is, if you want to undo the mysql_real_escape_string you can use stripslashes($sting) to remove it
PD: This is false and now i understand why.

Inserting Row in MySQL From Existing Row That Contains Quotes

Just wondering, to sanitize user input, I use mysql_real_escape_string() on data before it is inserted into a table. Therefore when a user enters something like this:
Hi I'm just testing this
It gets placed into the table just fine, exactly as above. Question is, if I were to pull that data and place it into a variable via PHP, say $string, what would happen if I then used that variable to insert data into a new row in the table? Such as:
<?php
$result = mysql_query( "SELECT data FROM table WHERE id='1'" ); //data = Hi I'm just testing this
$result_array = mysql_fetch_array( $result );
$string = $result_array['data']; //string = Hi I'm just testing this
$insert = mysql_query( "INSERT INTO table (data) VALUES ('$string')" ) or die(mysql_error());
?>
Would the single quote (') cause problems in this scenario? Should I be using $string = mysql_real_escape_string( $result_array['data'] ) in this case as well?
Thanks!
Once the data's pulled out of MySQL, it's just like any other piece of data that you want to use in a query: You have to do proper escaping/quoting, or use a prepared statement. There's no magical flag within PHP that says "this came from the database and shall return whence it came".
The alternative is to use the INSERT INTO ... SELECT FROM syntax to do the operation completely within the database, if you can meet the conditions.
mysql_real_escape_string() simply prepares it for insertion into the database, once you request that data again it will be in its original form, i.e. you will have to sanitize it again before trying to insert it like your example above.

Categories