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.
Related
I am trying to do a str_replace without success.. for some reason the data from MySql isn't working inside the str_replace function...
Code to bring all strings which will be used to replace the string:
$aspas = "'";
$sql2 = '
SELECT
GROUP_CONCAT(
DISTINCT CONCAT("'.$aspas.'", prefixo, "-'.$aspas.','.$aspas.'-", posfixo, "'.$aspas.'")
) AS prefixo_posfixo
FROM
profissionais
';
$stm2 = $pdo->prepare($sql2);
$stm2->execute();
$resultado = $stm2->fetch();
Produces with no error this output:
echo $resultado[0] >> 'dr-','-advogado','dra-','-advogada'
But when I try to insert inside the str_replace function :
$newstring = str_replace([$resultado[0]], '', 'dra-flavia-barao-advogada');
echo newstring >> dra-flavia-barao-advogada
As you see, the result keep the same, it doesn't replace the string ;(
I think it is something about convert the array to string, but the $resultado[0] isn't in a array format so I cant implode...
Do you know what I am doing wrong?
I forgot to post the solution before, There is:
//SELECT THE STRINGS TO BE USED TO REMOVE FUNCTION
$sql2 = '
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(prefixo, "-,-",posfixo)
) AS prefixo_posfixo
FROM
profissionais
';
$stm2 = $pdo->prepare($sql2);
$stm2->execute();
$prefixo_posfixo = $stm2->fetch();
//REPLACE / REMOVE THE STRINGS
$newstring = str_replace(explode(",", $prefixo_posfixo[0]), '', 'dra-flavia-barao-advogada');
//PRODUCES THE OUTPUT
flavia-barao
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.
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
I have a form which is a select multiple input which POSTs values like this: option1,option2,option3 etc..
How is the best way to convert this to 'option1','option2','option3' etc...
Currenty I'm doing this, but it feels wrong??
$variable=explode(",", $variable);
$variable=implode("','", $variable);
The reason why I'm doing this is because I want to use the form select multiple inputs in a SQL Query using IN.
SELECT * FROM TABLE WHERE some_column IN ('$variable')
You can wrap whatever code in a function to make the "feels wrong" feeling disapear. E.g.:
function buildSqlInClauseFromCsv($csv)
{
return "in ('" . str_replace(",", "','", $csv) . "') ";
}
If $variable = "option1,option2,option3"
you can use:
"SELECT * FROM TABLE WHERE FIND_IN_SET(some_column, '$variable')"
Here is what I used:
WHERE column IN ('".str_replace(",", "','", $_GET[stringlist])."')
we know that implode converts array to string,we need to provide the separator and then array as shown below, here we have (coma ,) as a separator.
Implode breaks each element of an array with the given separator,I have conceited '(single quotes) with the separator.
$arr = array();
$arr[] = "raam";
$arr[] = "laxman";
$arr[] = "Bharat";
$arr[] = "Arjun";
$arr[] = "Dhavel";
var_dump($arr);
$str = "'".implode("','", $arr)."'";
echo $str;
output: 'raam','laxman','Bharat','Arjun','Dhavel'
There is only one correct way to escape strings for SQL - use the function provided by the database api to escape strings for SQL. While mysyl_* provides mysql_real_escape_string():
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = "'".mysql_real_escape_string($choice)."'";
$choices = implode(",", $choices);
PDO provides a method that will add quotes at the same time:
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = $pdoDb->quote($choice);
$choices = implode(",", $choices);
Note that PDO::prepare doesn't really work here
I have a string of characters separated by many hashes (#). I need to get the individual words in between the hashes on php. here's what my code looks like:
$sql = "SELECT attribute_type.at_name,attribute_type.at_id FROM attribute_type
WHERE attribute_type.prodType_id = $pt_id
AND attribute_type.at_id NOT IN (SELECT at_id
FROM attribute_type
WHERE attribute_type.at_name = 'Product')";
while($items. strpos("#")>0){
// add the selected AT in every loop to be excluded
// .
// here tokens from $items are stored individually in
// $selectedAT (whose value changes in every loop/cycle)
//
// add to the current sql statement the values $at_id and $searchparam
$sql = $sql . "AND attribute_type.at_id NOT IN
(SELECT at_id FROM attribute_type
WHERE attribute_type.at_name = '$selectedAT')";
}
$dbcon = new DatabaseManager();
$rs = $dbcon->runQuery($sql);
explode creates an array by splitting a string on a given token
$words = explode("#", $items);
Now if you need to take these words you extracted from the string and use them to compare to some column in a SQL query...
$sql = "SELECT ... WHERE column IN ('" . implode("', '", $words) . "')";
You should not need to build a query in a loop as you are doing once you have the words in an array.
Even if you did want to do it that way, you don't want to create a subquery for every word when you could just OR the words together in one subquery.
Try strtok. Example paste:
$string = "This is\tan example\nstring";
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
Do not use split as suggested in another answer (which has now been updated). It uses old POSIX regulat expressions and it's deprecated.
To split a string, use $words = explode('#', $items); which does not use a regular expression but a plain string.
Docref: http://php.net/explode