Following is my code showing some error in mysql query:
<?php
$con=mysql_connect('localhost','root','');
$str=$_GET["message"];
$stor=explode(" ",$str);// converting message into array
mysql_select_db('words',$con);
for($j=0;$j<=30; $j++)
{
mysql_query($con,"UPDATE blacklist SET $stor=1 where $stor=0");//if column name=element in array then make it as 1 in database
}
mysql_close($con);
?>
Your code is vulnerable to SQL Injection. Read up on prepared statements and use PDO/MySQLi.
$stor is an array object and cant be used directly in the query. If you want to use it, try using
IN('.implode(",", $stor).')
the code above does the following:
implode() - takes an array and turns it into a comma separated string.
IN() - compares the given comma separated values and returns true if at least one of them exists.
Example (implode):
implode(",", array(1,2,3)) IS EQUAL TO "1,2,3"
Example (IN):
TestID IN (1,2,3) IS SAME AS (TestID = 1 OR TestID = 2 OR TestID = 3)
You're probably getting a mysql error because your query ends up looking like this
UPDATE blacklist SET Array=1 where Array=0;
If you're just echoing out a full array, you get Array instead, you'll need to specify an array element ($stor[1] for example).
What you'll want to do is replace your for loop with a foreach so that you can just throw out the elements one at a time.
Also, your arguments are backwards.
foreach($stor as $word)
{
mysql_query("UPDATE blacklist SET $word=1 where $word=0", $con);
}
Related
I'm running a PDO query, something like:
$inputArr = array(val1, val2, val3, ...);
$qMarks = str_repeat('?,', count($inputArr) - 1) . '?';
$stmt = $db->prepare("SELECT id, name, type, level
FROM table
WHERE name IN ($qMarks)");
$stmt->execute($inputArr);
... parse the rows that have been returned
And this works exactly as expected, no hang-ups or anything.
My problem is that I need to know which value from $inputArr was used to get each row returned.
I've tried
WHERE name IN ($qMarks) AS inputVal
and
WHERE name IN ($qMarks AS inputVal)
but those crash the query.
How can I determine which input array value was used to return each row in the output?
EDIT 1
Yes, I understand that the input search value would be name, for this particular case, but the query above is only for demonstration purposes of how I am putting the search values into the query.
The actual is much more complex, and returns any name value with is close (but not always identical).
The AS keyword is not going to work as you expect it. It's mainly used for aliasing subqueries. You can't (to my knowledge) use it in a WHERE clause.
The scenario you've outlined should have the 'name' in $row['name']. If it was a different variable that you wanted to see, you'd simply add it in your SELECT clause.
Great question, and simple answer:
The WHERE name IN $qMarks)"); part of your code is only obtaining the values in your database that are matching your array, so what you can do is see which values of name are present in the row you fetched. For example:
$rows_fetched = $stmt->fetchAll(PDO::FETCHASSOC);
$inputArray = array();
foreach($rows_fetched as $value)
{
$inputArray[] = $value['name'];
}
print_r($inputArray);//printing the results
Now you have the array $inputArray with all the values used to return each row in the output. Let me know if that worked for you!
for some odd reason php statement work fine when i only have on item in the array but everytime i add a second one i get an error "Column count doesn't match value count at row 1" I clearly have the correct column count. please help
$form_array=implode(",",array("james","brown"));
$db_array=implode(",",array('firstname','lastname'));
$query="INSERT INTO application ($db_array)
Value('$array')";
$dbquery=mysql_query($query);
if(!$dbquery){
echo mysql_error();
}
Your values are not quoted correctly. (and you're using $array instead of $form_array).
Note $form_array after imploding = 'james,brown'.
Putting that (and $db_array) into your query string, you end up with:
$query = "INSERT INTO application (firstname, lastname) VALUE ('james,brown');
Notice "james" and "brown" are quoted together in a single string - hence column count not matching value count.
You really should use a query string escaping function on your inputs - e.g. mysql_real_escape_string:
Wrote this off the top of my head so might have a minor syntax error somewhere, but the below example should push you in the right direction:
$form_array = implode(',', array_map('mysql_real_escape_string', array('james', 'brown')));
$db_array = implode(',', array('firstname','lastname'));
$query = "INSERT INTO application ($db_array) VALUES ($form_array)";
Note you should also take some more precautions if your $db_array is provided by user input in some way.
I am sending an array of numbers separated by commans to server. Basically on server database I have a field that cotains numbers.Server side code checks which numbers are in database and send me the array of those numbers.
Following code is what I am using...
public function already_user()
{
$contacts=$this->input->post('contact');
//$contacts is an array.
$user= explode(',',$contacts);
foreach($user as $number)
{
$data = array (
'username' =>$number
);
$usernumber = $this->chat_model->get(array('username'=>$number)); // a simple query to datbase that check if number exists in database column or not.
if(!$usernumber==""){
$value[]=$usernumber;
}
}
echo json_encode($value);
}
Only drawback about this code is , its extremely slow.... If i have 1000+ numbers it takes a minute.since its a loop Is there any way to fasten this up. Any single mysql query??
Why don't you just write a single query? Parse the string to get an array and query the table in a single go.
$contact_array = array_map('trim', explode(', ', $contacts));
$all_usernumbers = $this->chat_model->get(array('username IN'=> $contact_array));
which should (depending of what your chat_model->get() accepts), translate to:
SELECT * FROM your_table WHERE username IN ('123', '345')
This is all pseudocode since I don't know what your framework accepts but the SQL query above should be valid.
I am looking to use the contents of an array
$arr =array(24,28,30,34, 40);
and pass these into the where clause of a MySQL select statement, all my research has shown this done by using IN to pass in all the array values in one go.
I need to pass in each array element one at a time and then echo out the results of the SQL statement one at a time as the select statement is updated with the next array element.
New to programming and PHP so just need a little example to get me started...
Thanks to Zad highlighted the real issue
I need to pass each array value individually to a SQL statement as these need to be utilised in Where clause with BETWEEN, eg. WHERE age BETWEEN $array1 AND $array2 in order to determine count over an age range
thanks for all the input
You can use the implode function to build the string that contains the list;
$arr =array(24,28,30,34, 40);
$query = 'SELECT * FROM mytable WHERE id IN (' .implode($arr, ', '). ' )';
echo $query;`
http://codepad.org/tLPZxq8P
http://mx2.php.net/manual/en/function.implode.php
try it with escaping the argument
foreach($arr as $array_element) {
$query = 'SELECT * FROM table WHERE field = \''.mysql_real_escape_string($array_element).'\'';
//your statement
}
You can use a foreach function:
// make connection to mysql server
foreach ( $arr as $element ) {
$statement = "SELECT whatever FROM wherever WHERE something = $element"; // maybe a little validation here wouldn't hurt either
// execute statement
// process results
} // end of foreach
// close connection
$arr =array(24,28,30,34, 40);
$a = 'SELECT * FROM foo WHERE bar IN('.implode(',',$arr).')';
Edit: I'll admit, I didn't fully read the question, the title is misleading - consider changing that.
I need to pass in each array element one at a time and then echo out
the results of the SQL statement one at a time as the select statement
is updated with the next array element.
Could you explain how the scenario a bit better?
I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?
Remember to escape values:
'"' . implode('","', array_map('mysql_real_escape_string', $data)) . '"'
implode(',', $array);
Make sure you pass the results through mysql_real_escape_string() before executing your query. This should prevent sql injection if you use implode() as others suggest.
And as nickf mentions, always check to make sure the array isn't empty or null first, and handle those cases. Since you are only dealing with int's, it wouldn't hurt to put some type checking in your assignments, otherwise you'll get sql errors if a string slips in somehow.
Often this type of situation is people building an array from another table for use in a 2nd query.. If this is the case you can use a subquery to accomplish this.
Eg.
UPDATE Table SET Column = Value WHERE ID IN ( SELECT ID FROM Table2 WHERE CONDITIONS )
This is probably better if all ids should be numerical.
Check that it consists of at least one integer with
$ids = array_filter($ids, 'is_int');
if (!$ids) {
//no valid ids returned.
die('or something');
}
$sql .= '(' . implode(',', $ids) . ')';