Can't insert link into mysql database - php

Here is a part of my insert code that troubles me:
$recepient="test#email.com";
$text="Please track: http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&loc=en_US&Requester=UPSHome&tracknum=123456789&AgreeToTermsAndConditions=yes&ignore=&track.x=24&track.y=9";
$date="2013-05-03 08:12:20";
$through="mail";
$status=1;
$q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`) VALUES('".mysql_real_escape_string($to)."','".mysql_real_escape_string($text)."','".date("Y-m-d H:i:s")."','".mysql_real_escape_string($rowuser['through'])."','".intval($status)."')";
try {$db->query($q);} catch(PDOException $ex) {echp" Error: ".$ex.);}
If I remove the link from the $text variable I can see the data added to the database. But in the way I need it to add with the link - the script stops not reporting any errors.

use PDO's powerful prepared statements:
$q = "INSERT INTO messages (recepient,text,date,through,status) ";
$q .= "VALUES (:to,:text,:date,:through,:status)";
$dbinsert = $db->prepare($q);
$dbinsert->execute(array(
':to' => $recipient,
':text' => $text,
':date' => $date,
':through' => $through,
':status' => $status));
This should do it.
Let PDO take care of escaping.

It would appear that you're mixing database libraries, or have wrapped things yourself.
If you're using something like mysqli or PDO for the ->query() call, then mysql_real_escape_string() will NOT work. m_r_e_s() requires an active connection to the DB to operate. Connections established in mysql, mysqli, and PDO are NOT shareable between the libraries.
That means your m_r_e_s() calls will returning a boolean FALSE for failure, and your query will actually look like:
$q = "INSERT .... VAALUES ('', '', '', etc...)";

What's the size of the text column in the database? It's mostly not the reason but I've noticed that your $text is 190 char long.

The problem is with the "?" sign in the $text variable. It is being treated as a placeholder when it is put into the query, and the $db->query expects an array of variables.
The solution is to use a placeholder instead of a $text variable and submit $text variable as params:
$ar[0]=$text;
$q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`)";
$q.= " VALUES('".$to."',?,'".date("Y-m-d H:i:s")."','".$through."',".$status.")";
$db->query($q,$ar);

Related

htmlspecialchars function mixed with parameter binding/statement preparing is resulting in /r and /n showing

In a project I am working on for PHP and Mysqli, I have to use prepare and bind_param to for my mysqli statements. I wrote these statements before doing so and they work fine. This is before binding and preparing.
$sql = "INSERT INTO comments (commentid, userid, comment, commentdate)
VALUES (NULL, '".$_SESSION["userid"]."', '" . htmlspecialchars($comment, ENT_QUOTES) . "', CURRENT_TIMESTAMP)";
$conn->query($sql);
In the textarea where I write a comment, if I use enter and move to next line, the output would be something like:
Old Line New Line
Now, when I start binding values and preparing the statement my output gets a bit strange. Here is the code for that:
$userid = $_SESSION['userid'];
$stmt = $conn->prepare("INSERT INTO comments (commentid, userid, comment, commentdate)
VALUES (NULL, ?,?, CURRENT_TIMESTAMP)");
$stmt->bind_param("is", $userid, htmlspecialchars($comment, ENT_QUOTES));
$stmt->execute();
For some reason after doing it this way if I created a new line within the text are the output would be as follows:
Old Line/r/nNew Line
Is there something I am doing wrong that I can fix so that /r/n is not outputted to the page? Thanks for any help!
The solution to my problem I found had nothing to do with the html special characters within the bind param. It was the fact that I was already using mysqli_real_escape_string to retrieve the comment. If you already have escaped your string then there is no need to bind it but also you can just bind it without escaping! Either works.
Those line breaks entered into the textarea input field are converted by the htmlspecialchars() function into \r\n.
First, to remove the \r\n, you can use str_replace()
$escape_comment = htmlspecialchars( $comment, ENT_QUOTES );
$remove_line_breaks = str_replace( "\\r\\n", '', $escape_comment );
Or, instead of using htmlspecialchars(), why not use strip_tags(), then you can decide which tags are allowed in comments. Note:Unless you know that the comment content will be formatted properly, you may not want to use strip_tags()
$escape_comment = strip_tags ( $comment, '<a><p><i><strong><li>' );

PHP: Error when inserting quotation marks in mySQL

I insert a text variable in a mySQL table. Everything works fine except in the text is a quotation mark. I thought that I can prevent an error by using "mysql_real_escape_string". But there is an error anyway.
My insert statement:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_real_escape_string($insertimage);
The error message:
MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1413885955514','10')' at line 1
You need to escape data that you are putting into the SQL so that any special characters in it don't break the SQL.
You are escaping all the special characters in the final string of SQL; even those that you want to have special meaning.
If you want to use your current approach, you would do something like this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
… but the PHP mysql_ extension is obsolete and you shouldn't use it.
Modern APIs, such as mysqli_ and PDO support prepared statements, which are a better way to handle user input. This answer covers that in more detail.
The problem with your current code is that you have not correctly escaped the values you're trying to enter into the table.
Better still is to avoid the mysql_* function family entirely. Those functions are now deprecated and bring security risks to the table (along with other concerns).
You'd be better to use PDO and Prepared Statements, for example:
$db = new PDO('param1', 'param2', 'param3');
$sql = $db->prepare( 'INSERT INTO `image` (`filename`, `text`, `timestamp`, `countdown`)
VALUES (:filename, :text, :timestamp, :countdown)' );
$sql->execute( array(':filename' => $filename,
':text' => $text,
':timestamp' => $timestamp,
':countdown' => $countdown )
);
mysql_real_escape_string($insertimage);
You will have to use this function to each variables before writing the query.
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
Try this ,
$insertimage = sprintf("INSERT INTO image(filename,text,timestamp,countdown) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($filename), mysql_real_escape_string($text), $timestamp, $countdown);
Why, because your inputs vars must be escaped before using them in sql
then execute your sql.
Escaping the entire query is not useful. In fact, right now, you are causing syntax errors by doing so.
You should be escaping the individual variables that you inject into it.
Try this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage = "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_query($insertimage);
Concat the php variables like this:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES (" . $filenamec . "," . $text . ", " . $timestamp . ", " . $countdown . ")";
with the respective single quotes in those that are text fields i.e: "... '" . $text . "' ..."

issue performing an INSERT statement with mysql_query() PHP

basically I am trying to implement a function in one of my PHP classes that makes an entry into a junction table for a many to many relationship.
This is the method here:
public function setTags($value, $id){
global $db;
$tags = $value;
$query .= "DELETE FROM directorycolumntags
WHERE directorycolumn_id = $id; ";
foreach($tags as $tag){
$query .= "INSERT INTO directorycolumntags (directorycolumn_id, tag_id)
VALUES (".$id.",".$tag.");";
}
mysql_query($query);
}
The SQL is produces works fine, as I've echoed it and manually executed it via phpMyAdmin. However, If I leave it as above, the data is never inserted. Does anyone know why this might be happening?
This is the sql it is generating which works fine when I type it manually in:
DELETE FROM directorycolumntags WHERE directorycolumn_id = 178;
INSERT INTO directorycolumntags (directorycolumn_id, tag_id) VALUES (178,29);
INSERT INTO directorycolumntags (directorycolumn_id, tag_id) VALUES (178,30);
INSERT INTO directorycolumntags (directorycolumn_id, tag_id) VALUES (178,32);
The old, unsafe, deprecated mysql_* extension never supported multiple queries. You could, conceivably do this using the mysql replacement extension: mysqli_*, which has the mysqli_multi_query function.
Personally, I'd not use this approach, though. I'd do what most devs would do: use a prepared statement in a transaction to execute each query safely, and commit the results on success, or rollback on failure:
$db = new PDO(
'mysql:host=127.0.0.1;dbname=db;charset=utf8',
'user',
'pass',
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
try
{
$db->beginTransaction();
$stmt = $db->prepare('DELETE FROM tbl WHERE field = :id');
$stmt->execute(array(':id' => $id));
$stmt = $db->prepare('INSERT INTO tbl (field1, field2) VALUES (:field1, :field2)');
foreach ($tags as $tag)
{
$stmt->execute(
array(
':field1' => $id,
':field2' => $tag
)
);
$stmt->closeCursor();//<-- optional for MySQL
}
$db->commit();
}
catch (PDOException $e)
{
$db->rollBack();
echo 'Something went wrong: ', $e->getMessage();
}
Going slightly off-topic: You really ought to consider using type-hints. From your code, it's clear that $values is expected to be an array. A type-hint can ensure that the value being passed is in fact an array. You should also get rid of that ugly global $db;, and instead pass the connection as an argument, too. That's why I'd strongly suggest you change your function's signature from:
public function setTags($value, $id){
To:
public function setTags(PDO $db, array $value, $id)
{
}
That way, debugging gets a lot easier:
$instance->setTags(123, 123);//in your current code will not fail immediately
$instance->setTags($db, [123], 123);//in my suggestion works but...
$instance->setTags([123], null, '');// fails with a message saying argument 1 instance of PDO expected
http://docs.php.net/mysql_query says:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier
If you can use mysqli perhaps this interest you: mysqli.multi-query
Executes one or multiple queries which are concatenated by a semicolon.
you can not run multiple quires using mysql_query, try to modify your function like this. It would be better if you use mysqli or pdo instead of mysql because soon it will deprecated and it would not work on newer version of php
public function setTags($value, $id){
global $db;
$tags = $value;
mysql_query("DELETE FROM directorycolumntags WHERE directorycolumn_id = $id");
foreach($tags as $tag){
mysql_query("INSERT into directorycolumntags (directorycolumn_id, tag_id) VALUES (".$id.",".$tag.")");
}
}

MySQL INSERT INTO doesn't do anything - not even error

I have this query:
mysql_query("INSERT INTO `63_Activity` (`username`, `time`) VALUES (`$usernann2`, `$date`)");
However, it doesn't do anything. Even when I tried correcting the variables to
". $variable ."
I checked the variables.
I copied the little line of code from somewhere it works.
The database and tables are existing.
I just thought I had things under control, then that happened -.-
Thank you in advance.
PS: I tried adding or die() - but no error. Nothing.
Values need to be in single quotes ('), not backticks (`)
mysql_query("INSERT INTO `63_Activity` (`username`, `time`) VALUES ('$usernann2', '$date')");
You should also make sure you're sanitizing your inputs, as well as preferably not using the mysql_ functions in place of mysqli_
You would be better off using Paramaterized queries as in the following example:
<?php
try {
$usernann2 = "whateverUsernameFits";
$date = new DateTime('2000-01-01');
$stmt = $this->db->prepare ( "INSERT INTO 63_Activity (username, time) VALUES (:usernann2, :date)");
$stmt->bindParam ( ':usernann2', $usernann2 );
$stmt->bindParam ( ':date', $date );
$stmt->execute ();
}catch ( PDOException $e )
{
throw new Exception ( $this->db->errorInfo () . 'Problem inserting object ' );
} catch ( Exception $e ) {
throw new \Exception ( 'Problem inserting object ' );
}
?>
Bound parameters are a staple in preventing SQL Injection attacks. The exceptions thrown would give you a clue as to what might be the problem in your query if there is one. I normally check the query first to make sure it's working with real values. From there it is a process of elimination.
PS. https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet for more information on SQL Injection. You should also be able to find some excellent information and questions here on Stackoverflow regarding SQL Injection.
try to put the query in a variable and echo it, and see if anything wrong, try to run it on php my admin also

Oracle-00972 : identifier too long what's wrong with my SQL?

<?php
// This leaves the db connection in $conng require_once('/tms/http/html_docs/tease/csp/csp_tease.php');
/* This a logging function. When called with:
*/
function log_tkt_to_db($tkt_number, $date, $uid, $description, $conng)
{
echo "$tkt_number|$date|$uid|$description<br>";
$sqlinsert = "insert into TEASE_TKTLOGS VALUES ( \"$tkt_number\", \"$date\", \"$description\", \"$uid\")";
echo $sqlinsert . "<br>";
$insert = OCIParse($conng, $sqlinsert);
// OCIExecute($insert, OCI_COMMIT_ON_SUCCESS);
OCIExecute($insert);
}
log_tkt_to_db("00000000", "07/13/2012", "jt898u", "this a test, this is only a test", $conng);
?>
I get this output:
00000000|07/13/2012|jt898u|this a test, this is only a test
insert into TEASE_TKTLOGS (TICKET, DATE_TIME, CHANGE_DESC, ATTUID) VALUES ( "00000000", "07/13/2012", "this a test, this is only a test", "jt898u")
Warning: ociexecute() [function.ociexecute]: ORA-00972: identifier is too long in /appl/tms/http/html_docs/tease/dblog.php on line 17
There are multiple things wrong here.
The simplest answer is that you need to use single quote marks (') instead of double quotes (see String Literals in Oracle Database SQL Reference)
You really should use something like oci_bind_by_name instead of blindly inserting your values into the query. Saves you a parse and a potential SQL injection.
ociparse and ociexecute are deprecated as of PHP 5.4. Instead of these you should use, respectively, oci_parse and oci_execute.

Categories