I want to have a string with the char ' in it, without having it closing the string:
$title = "google";
$link = "www.google.com";
$val_str = "'" . $title . "'," . $link . "'";
$query = "INSERT INTO MY_TABLE (title,link) . VALUES (" . $val_str . ")";
so that $val_str will have: 'google', 'www.google.com'
in it.
how can i do it?
You can use a backslash to escape the ' character in your string:
echo 'Hello: "I\'ll be back"';
Escape it with a \.
i.e. \'google.com\'
You could just do this:
$query = "INSERT INTO MY_TABLE (title,link) VALUES ('$title', '$link')";
If $title and $link is not under your control, then you need to escape them.
Related
I want to allow a user to search a table by selecting a field name from a dropdown list, then entering the term to search for in that field. The problem I'm having is that some fields are strings and some are numbers. When I construct the WHERE clause from the $_GET variables, I don't know how to delimit the search term because I can't come up with a good way to determine if the field selected by the user is numeric or string.
This is the search form:
<form action="<?php $_SERVER['PHP_SELF'] ?>">
<label for="search_field">Search:</label>
<select name="search_field">
<?php
$fields = $res->fetch_fields();
foreach($fields AS $f) {
echo '<option value="' . $f->name . '">' . $f->name . '</option>\n';
}
?>
</select>
<label for="search_for">For:</label>
<input type="text" name="search_for" />
<input type="submit" value="Search" />
</form>
The php file processes the search variables like this:
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
$sql_where = "AND " . $_GET['search_field'] . ' = ' . $_GET['search_for'] . ' ';
}
$sql = $sql . $sql_where;
The query works fine for numeric fields, but not string fields. I could put quotes around the search_for term, but then numeric fields wouldn't work. There has got to be a way to do this. Any ideas? Thanks.
Just use is_numeric function to determine if its an number or string:
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
if(is_numeric($_GET['search_for']))
$sql_where = 'AND ' . $_GET['search_field'] . ' = . $_GET['search_for'] . ';
else{
$sql_where = 'AND ' . $_GET['search_field'] . ' = ' . '.$_GET['search_for'] . ' ';
}
}
You can check if $_GET['search_for'] is numeric in php using is_numeric
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
$sql_where = "AND " . $_GET['search_field'] . ' = ' .
(is_numeric($_GET['search_for']) ? $_GET['search_for'] : '"' .
$_GET['search_for'] . '"' ) . ' ';
}
Also if you always delimit the search_for with quotes it will work with numeric values you can try it. I just wanted to show you the is_numeric function as well
You know your code has security problems, don't you?
But to solve your problem just do
$search_for = is_numeric($_GET['search_for'])?$_GET['search_for']:"'".addslashes($_GET['search_for'])."'";
$sql_where = 'AND `' . $_GET['search_field'] . '` = ' . $search_for . ' ';
can someone help me on how to remove spaces in my sql.
for exmaple
let say i type in "I am a good boy"... i want it to save in my mysql table column as "iamagoodboy" removing all spaces of anything i send.. where in this code below can i do this, thanks very much
$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time) VALUES ("' . $username . '", "' . $messageTo . '", "' . $message . '", ' . $time . ')';
$result = mysql_query($sql, $cn) or
die(mysql_error($cn));
str_replace(' ', '', $message);
Should work fine for you in PHP. As a general rule, don't put that sort of functionality on the Database, no reason to put the load on that server - do it on the web server instead.
So your code would look like this (assuming you are taking the spaces out of $message):
$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time) VALUES ("' . $username . '", "' . $messageTo . '", "' . str_replace(' ', '', $message) . '", ' . $time . ')';
A better solution, though, might be to use preg_replace('/\s+/', '', $string); which will strip all whitespace (tabs, linebreaks, etc). Depends on what exactly you want to accomplish.
Use str_replace:
$string = str_replace(' ', '', $string);
or remove all whitespace
$string = preg_replace('/\s+/', '', $string);
source: How to strip all spaces out of a string in php?
You can replace characters using SQL ->
SELECT REPLACE(caption,'\"','\'') FROM ...
u can try this
'".str_replace(' ', '', $messageTo)."'
and same for other
$sql = 'INSERT INTO messages " .
. "(username,usernameto,message_content,message_time) " .
. "VALUES ("'.$username.'","'.$messageTo.'",REPLACE("'.$message.','' '','''')",'.$time .')';
$result = mysql_query($sql, $cn) or die(mysql_error($cn));
I'm having issues with apostrophes in GET arrays. I can't seem to escape single quotes. I've trawled through similar SO topics for over a day now with no luck. I think this may be something to do with my connection to the database as if I make a plain unconnected php page both addslashes and str_replace successfully escape single quotes in GET variables (mysqli_real_escape_string doesn't since there is no database connection).
PHP 5.2.17
Mysql 5.5.23
Magic_quotes is off
The connection:
DEFINE ('database', 'dbname');
DEFINE ('user', 'dbusername');
DEFINE ('pass', 'dbpassword');
DEFINE ('host', 'localhost');
$dbc = #mysqli_connect (host, user, pass, database) OR die ('Could not connect to database: ' . mysqli_connect_error() );
The database appears to be connected, select queries involving GET variables that do not have single quotes in work fine. However, now when a GET containing a single quote is passed, I can't seem to escape it.
print_r($_GET);
echo "<br><br>";
$text = "O'Reilly";
echo "Normal variable called text: " . $text . "<br>
addslashes(): " . addslashes($text) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $text) . "<br>
str_replace(): " . str_replace("'", "\'", $text) . "<br>
<br>";
echo "_GET variable: " . $_GET['breed'] . "<br>
addslashes(): " . addslashes($_GET['breed']) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $_GET['breed']) . "<br>
str_replace(): " . str_replace("'", "\'", $_GET['breed']) . "<br>
<br>";
$_GET['breed'] = "O'Conner";
echo "_GET variable with new value: " . $_GET['breed'] . "<br>
addslashes(): " . addslashes($_GET['breed']) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $_GET['breed']) . "<br>
str_replace(): " . str_replace("'", "\'", $_GET['breed']) . "<br>
<br>";
gives:
Array ( [breed] => Cirneco dell'Etna )
Normal variable called text: O'Reilly
addslashes(): O\'Reilly
mysqli_real_escape_string(): O\'Reilly
str_replace(): O\'Reilly
_GET variable: Cirneco dell'Etna
addslashes(): Cirneco dell'Etna
mysqli_real_escape_string(): Cirneco dell'Etna
str_replace(): Cirneco dell'Etna
_GET variable with new value: O'Conner
addslashes(): O\'Conner
mysqli_real_escape_string(): O\'Conner
str_replace(): O\'Conner
The single quote in Cirneco dell'Etna is definitely a single quote, not ` etc. I also tried urlencode() and urldecode() - it replaced spaces with + but did not escape the single quotes. The GETs need single quotes to make user-friendly URLs - usernames and (in this case) breed names for example; Cirneco dell%39Etna is not intuitive. It's not a complex site at all but single quotes crop up a lot as ownership is a major part of the site, so I'd like to work out what's happening!
I have tried switching to PDO but found it beyond me - I'm a novice programmer and my attempt at PDO was mind-boggling to troubleshoot - I can't tell whether errors in PDO are my typos, or a continuation of this same issue.
Many thanks.
EDIT
The select query (which works as expected for _GET variables without single quotes in) is constructed as follows:
$q = "SELECT breed_name, breed_type from b_breed
where breed_name = '" . $_GET['breed'] . "'
LIMIT 1";
$result = mysqli_query($dbc,$q);
if($result->num_rows == 0)
{
}
else
{
$row_breed = mysqli_fetch_array($result, MYSQLI_ASSOC);
{
echo "<h1>" . $row_breed['breed_name'] . " - " . $row_breed['breed_type'] . "</h1>";
}
}
I have tried including addslashes, mysqli_real_escape_string and str_replace (not at the same time) with the $_GET within the query, to no effect. If I echo $q, the single quote is never escaped.
SELECT breed_name, breed_type from b_breed where breed_name = 'Cirneco dell'Etna' LIMIT 1
Oddly, if I switch the double and single quotes so I have:
$q = 'SELECT breed_name, breed_type from b_breed
where breed_name = "' . $_GET['breed'] . '"
LIMIT 1';
SELECT breed_name, breed_type from b_breed where breed_name = "Cirneco dell'Etna" LIMIT 1
It still returns no rows on the page, although the echoed $q will return rows in PHPMyAdmin.
EDIT Solved!
It was changing the ' in the database to an ASCII character. Adding the following converted it back to ', which could then be escaped:
$_GET['breed'] = htmlspecialchars_decode($_GET['breed'], ENT_QUOTES);
You can check what are You getting from GET
try
$string = $_GET['breed'];
for ($i=0;$i<strlen($string);$i++) {
echo '<br>'.$string[$i].' : '.ord($string[$i]);
}
I wanted to write some variables to a file to include them in another script. But i get these errors while running the script:
Notice: Undefined variable: host in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
Notice: Undefined variable: database in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
Notice: Undefined variable: user in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
Notice: Undefined variable: password in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
HTML form:
<html>
<head>
<title>Contact installatie</title>
</head>
<body>
<h1>Contact installatie</h1>
<h2>Database gegevens:</h2>
<form name="databasesettings" action="writeconfig.php" method="post">
Host: <input type="text" name="host"> <br>
Database: <input type="text" name="database"> <br>
User: <input type="text" name="user"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Generate config">
</form>
</body>
</html>
And PHP code:
<?php
$config = "$host = " . $_POST["host"] . "\n$database = " . $_POST["database"] . "\n$user = " . $_POST["user"] . "\n$password = " . $_POST["password"];
$configfile=fopen("config.txt","w+");
fwrite($configfile, $config);
fclose($configfile);
?>
Use single quotes for literal strings. Or escape them "\"
Options:
Escape the $ with a backslash \
Use single quotes instead
Examples:
$config = "\$host = " . $_POST["host"] . "\n\$database = " . $_POST["database"] . "\n\$user = " . $_POST["user"] . "\n\$password = " . $_POST["password"];
$config = '$host = ' . $_POST["host"] . "\n" . '$database = " . $_POST["database"] . "\n" . '$user = " . $_POST["user"] . "\n" . '$password = " . $_POST["password"];
When using single quotes special characters like \n will also need special consideration. I just put them in double quotes in my example but you can escape them as well.
You have two options to get around this problem.
Double quoted strings in PHP perform variable name replacement (and more advanced replacements when wrapped with curly braces). You can instead use single quoted strings to be able to use $ within it, like so:
$config = '$host = ' . $_POST["host"] . "\n" . '$database = ' . $_POST["database"] . "\n" . '$user = ' . $_POST["user"] . "\n" . '$password = ' . $_POST["password"];
Note that you will have to put the \ns into double quoted strings, otherwise it won't be replaced properly.
Another alternative is to escape (using \) your $s, like this:
$config = "\$host = " . $_POST["host"] . "\n\$database = " . $_POST["database"] . "\n\$user = " . $_POST["user"] . "\n\$password = " . $_POST["password"];
As a bonus, if you wanted to use the braces as I mentioned above, you could write your string like so:
$config = "\$host = {$_POST['host']}\n\$database = {$_POST['database']}\n\$user = {$_POST['user']}\n\$password = {$_POST['password']}";
That doesn't mean I would recommend you to do so, though :)
The best way to do this is probably using sprintf, which makes it slightly more readable like so:
$config = sprintf("\$host = %s\r\n\$database = %s\r\n\$user = %s\r\n\$password = %s",
$_POST['host'], $_POST['database'], $_POST['user'], $_POST['password']);
When using double quotes ( " ) to wrap a string, PHP will attempt to replace any variable names ($variable) in the string with their values. If you don't want PHP to do that, use single quotes ( ' ) to wrap the string.
For more information, read about string in the PHP manual:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
http://php.net/manual/en/language.types.string.php#language.types.string.parsing
A side note, PHP won't do any interpreting of strings that use single quotes. So \n will not work in a single quoted string, it will need to be in a double quoted string.
"$var" will try to find variable $var;
Try to read this http://php.net/manual/en/language.types.string.php
When you use the '$' inside double quoted string, php assumes it as a variable and replaces it with it's value. So your options are escaping them using a '\' before it or use a single quoted string.
I recommend using a '\', as you can't always go for the second option.
I'm moving the reply as answer here. May be it'll help others.
hi friends why this php string error ?
echo '<div id="album_list">' . $i . ' ' . $v['album_name']. '</div>';
You have some missing single quotes.
echo '<div id="album_list">' . $i . ' ' . $v['album_name']. '</div>';
// you need a single quote here ^ ^ and here
You are missing a single-quote after album_pix/ and before the closing bracket.
echo '<div id="album_list">' . $i . ' ' . $v['album_name']. '</div>';
Single quote the string with the double quotes and attributes
Single space and concatenate with the period .
Change $var['key'] to $var, or $var["key"]
I'd change your variable names to reduce the confusion. As someone said above syntax highlighting will turn all the strings one color, and the variables another. Stack Overflow even displays code as such.
<?php
$v_id = $v['id'];
$v_album_name = $v['album_name'];
echo '<div id="album_list">' . $i . ' ' . $v_album_name . '</div>';
?>