Replace this ' character when queried to my PHPMYADMIN - php

Here is my PHP Code
It cannot be save to my database I wonder why..
txt = str_replace("♣","'", $string);

First of all write your insert query then we can tell what is the issue
Also you are assigning return value to a variable while variable name doesn't start with $
Change
txt = str_replace("♣","'", $string);
to
$txt = str_replace("♣","'", $string);

Please use function mysql_real_escape_string
$txt = str_replace("♣","'", $string);
$query = "INSERT INTO tbl_contents( functionname,editorcontent) VALUES('". $name ."','". mysql_real_escape_string($str) ."')";
$res = mysql_query($query,$con); //DO QUERY
For more detail read http://in1.php.net/mysql_real_escape_string

Related

comma separated if value in array is empty

I am stuck with a problem, I have fetched some values from a MySQL query and put them in to an array like so:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = rtrim(implode(',', $fullAddress), ',');
echo $string;
so that I can echo out a users address. The problem I am getting is that even if one of these values does not exist (and some don't because they are not all required fields), the comma is still echoed to the screen like:
add1,, town, br2 5lp
because there is an empty value in the database.
What I want to achieve is something like:
add1, town, br2 5lp
if the second part of the address is missing.
Can anyone help me figure this out?
try this.
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = implode(',', array_filter($fullAddress, 'strlen'));
echo $string;
The problem I am getting is that even if one of these values does not
exist (and some dont because they are not all required fields),
the comma is still echoed to the screen
That is what the implode function in php is supposed to do. If you want a different behavior, you will have to either change the way you create your CSV string or do some extra processing on the information you obtain from the implode function.
So use a for loop or a foreach loop to go through the address array. A for loop is faster than a foreach loop.
Using Foreach:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = "";
foreach($fullAddress as $value)
{
if(!empty($value))
$string .= $value.", ";
}
$string = rtrim($string, ", ");
echo $string;
You can do some extra processing on the created csv string of your own solution by maybe doing a str_replace() of all occurances of ,, with ,. This could be dangerous because if any of the values in your $fullAddress array contain a ,, as a valid string then that will also be replaced too with ,.
What you need is to assure array $fullAddress have no empty value, so php built-in function array_filter make this purpose very easy.
Just change your last codes to:
$string = implode(',', array_filter($fullAddress));
echo $string;
If the second parameter of array_filter is not supplied, all entries of array equal to FALSE will be removed. So just simply use array_filter($fullAddress) it make the code more clear and simple.

Accessing arrays created by explode function in php

I'm a beginner in PHP and mySQL. I pass a string to the PHP with AJAX and then I split the string after new lines. Later I assign each element in the array to a variable. I want to pass the variables to mySQL database.
Please assume:
$q = "John \n Doe \n 07589334009 \n john.doe#john.com";
Here is my attempt:
$date = date('Y/m/d H:i:s');
$q = $_REQUEST["q"];
$arr = explode(PHP_EOL, $q);
$name = $arr[0];
$surname = $arr[1];
$phone = $arr[2];
$email = $arr[3];
$sql = "INSERT INTO `database`.`myTable` (`Name`, `Surname`, `Phone`, `Email`, `reg_date`, `Valid`)
VALUES ('$name' , '$surname', '$phone', '$email', '$date', '1');";
$result = $conn->query($sql);
When I check my database I only see "JohnDoe07589334009john.doe#john.com" in the name column. Apart from that name and valid are columns are okay.
Just try to do it like
$arr = explode("\n", $q);
$name = $arr[0];
$surname = $arr[1];
$phone = $arr[2];
$email = $arr[3];
Explode using \n and remove spaces from it after exploding
PHP_EOL is not necessary to be "\n", it's a constant holding the line break character used by the server platform. Therefore, it can be used when you are writing to the file system such as logs but not as an equivalent to "\n".
So, you have to replace PHP_EOL with "\n"

Removing single quotes in PHP

I got some issues trying to INSERT some data from a php document till i got 2 values which contains quotes inside like :
"Rempli d'étoiles"
i d like to remove the ' by a space or even nothing.
-> "Rempli d etoiles"
Here is my what i tried :
$posdeapostrophe = strpos($array, '\'');
if ($posdeapostrophe == false)
{
...
}
else
{
// it goes in this block when it detects a ', but seems like trim doesnt work as i would
$newchaine = trim($array, '\'');
$sql .= "INSERT INTO categorie (id_cat,name_cat) VALUES (" . $cpt . ",'" .$newchaine . "'); ";
thanks!
You can use str_replace().
$array = "Some string's";
$posdeapostrophe = strpos($array, "'");
$val = '';
if ($posdeapostrophe !== false)
{
$val = str_replace("'", "\'", $array);
}
echo $val;
Also can use instead of strpos() and replace() to escape single quotes.
mysqli_real_escape_string($con, $array ); //for mysqli
mysql_real_escape_string($array , $con); //for mysql
What you are currently doing is quite dangerous.
First of all, you should really use the current recommended method for executing queries which is by using PDO: http://php.net/manual/en/book.pdo.php
This will both solve the quotes problem and a massive security hole (SQLi vulnerability) you have currently introduced in your code.
If you still want to replace the single quotes in your text you can indeed do what #scrowler suggested which is:
$your_string = str_replace("'", "", $your_string);
But please use PDO when interacting with a database since this is really the only (safe and recommended) way of doing this.

PHP error while inserting in MYSQL with arrays

I have a script which inserts all data in array to MYSQL. But when there is just a single word in the array, the script gives no error, while when there are multiple words, it gives a
Column count doesn't match value count at row 1
Here is my code
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
include("connect.php");
$counter = 0;
$counters = 0;
$string = mysql_real_escape_string($_POST['words']);
$arr = explode(" ", $string);
mysql_query("SET charset utf8");
$sql = mysql_query("SELECT `word` FROM unicode WHERE word IN ('".implode("', '", $arr) . "')") or die (mysql_error());
$dupes = array();
while($r = mysql_fetch_assoc($sql)) {
$dupes[] = $r['word'];
}
$newwords = array_diff($arr, $dupes);
if(count($newwords)) {
$word = implode("'),('", $newwords);
$md5 = md5($word);
$sqli = mysql_query("INSERT INTO unicode (word, word_hash) VALUES ('$word', '$md5')") or die (mysql_error());
}
}
?>
Please help....
As a rule, when I have problems with SQL I do the following things to track down the issue.
ECHO out the SQL query I am trying to run against the DB. This makes sure that I am passing the value of the variable and not the the text '$variable'.
Switch on and check the general.log table in the MySQL DB (assuming you are using MySQL). This will show you the last queries run against the DB and will prove one way or another if your script is even executing anything against the DB.
Lastly I am not as au fait with imploding etc as suggest above to comment, however I would also add the following. Looking at your query it looks as if you are doing I what I talked about in point 1.
$sqli = mysql_query("INSERT INTO unicode (word, word_hash) VALUES ('$word', '$md5')") or die (mysql_error());
The single quotes around $word and $md5 would mean literally pass $word and $md5 into the DB. When using variables within double quote " ... " you do not need to put anything around them just use them as is. Or if you would like to use single quote marks you can concatenate the query string.
$sqli = mysql_query('INSERT INTO unicode (word, word_hash) VALUES ( ' . $word . ', ' . $md5 . ')') or die...
Again echo out the query as you have it (without the mysqli_query function) to confirm.
Hope this helps.
S
You're imploding $newwords, so the resulting query would look something like:
...VALUES ('word1'),('word2'),('word3', 'md5 string')
Add $md5 to implode():
$md5 = 'md5 string';
$word = implode("', '$md5'),('", array('word1', 'word2', 'word3'));
Outputs:
...VALUES ('word1', 'md5 string'),('word2', 'md5 string'),('word3', 'md5 string')
The number of column parameters in your INSERT query is more than 2, but you've only provided 2 values.
$word = implode("'),('", $newwords);
This statement here is the culprit. When you implode the $newwords array, you'd probably get more than 2 values. When inserted into the MySQL query, it won't match with the number of VALUES you've provided. That's causing the error.

How do I remove the apostrophe before inserting into MYSQL? (not simply escaping them)

i have a program that fetches titles of webpages that sometimes have apostrophes. i don't simply want to comment them out and escape them with \s. how can i get rid of them all together?
str_replace() should work:
$string = str_replace("'", "", $string);
You may use this function to clean up titles from any unwanted characters.
function clean_up( $text ) {
$unwanted = array("'"); // add any unwanted char to this array
return str_ireplace($unwanted, '', $text);
}
Use it like:
$dirty_title = "I don't need apostrophes.";
$clean_title = clean_up($dirty_title);
echo $clean_title; // outputs: I dont need apostrophes.
$string = str_replace("'", "'", $string);
This method is PHP & MySQL safe and doesn't alter the appearance of the string when it's echoed. Useful when dealing with names like O'Brian.
If you want to insert a string that contains apostrophes, add below line in code that will escape them:
$data = str_replace("'", "\'", $data);
if you try to trim before mysql update, or insert into ...
$string = str_replace("'", "", $string);
is fine but mysql can use another sign instead of trimmed one.
Here what I developed is trimming after echoing mysql value.
Reading from mysql:
$result = mysqli_query($conn, "SELECT value1 FROM db WHERE id='1' ");
if (mysqli_num_rows($result) > 0) {while($row = mysqli_fetch_assoc($result)) {
echo str_replace('"', '', $row["value"]);
}
}

Categories