I want to return all the rows from a specific table when a specific column value is contained in a PHP variable, e.g : row 34: has column 'xyz' value equal to = "rabbit" and my php variable is $var = "rabbit,robert,teen", and because the "xyz" column value is contained in $var I want it to be selected.
How can I do that?
convert the comma separated list to sql format and place in the query
$query = "select blah blah WHERE xyz IN ('".str_replace("," ,"','", $var)."');"
If I understand your question correctly, you're looking for something like this:
$arr = explode(',', $var);
$where_in_val = '';
foreach($arr as $value){
$where_in_val.= "'$value',";
}
$where_in_val = substr($where_in_val,0,-1);
Then your query might be something like this
SELECT * FROM my_table WHERE xyz IN ($where_in_val)
Note: Don't forget cleaning/escaping/sanitizing the user's input.
Related
I have a site were the user fills a form and all data is stored in a database, when the user enter his/hers page all the added data is visible. Today I´m doing this but in a lot of code rows and there is for sure a much smoother way to do this.
Here´s a look of how I have done it today:
$query = mysqli_query($dbhandle, "SELECT * FROM ..."); // ... added now
$row = mysqli_fetch_assoc($query);
$m0 = $row['m1'];
$m1 = $row['m2'];
$m2 = $row['m3'];
$m3 = $row['m4'];
...
$m47 = $row['m48'];
$firstPlace = $row['firstPlace '];
$secondPlace = $row['secondPlace '];
$thirdPlace = $row['thirdPlace '];
$fourthPlace= $row['fourthPlace'];
As you can see there are a lot of rows of code. What I would like to do is to loop through my query and then add the right value in the database to the right value in the form.
Appreciate help.
There definitely are many alternative (and in every possible sense of the word) better ways to go about your business.
For a kickoff: ask yourself what an array actually is. An array is a collection of data. You store them together because one value of that array in itself doesn't mean much. The data in an array belongs together. Why then, assign it to individual variables in the first place?
Of course, your $row array has keys like $row['m1'], which you assign to a variable called $m0. so the names of the fields in the database don't quite match the names your code uses. That's something that you can, quite easily, fix by changing your query: use aliasses for those fields:
SELECT m1 as m0, ... FROM
Now your array will have a key called m0, instead of m1. This reduces the rest of your code down to:
$row = mysqli_fetch_assoc($query);
echo 'M0: ', $row['m0'];//<-- use m0 value here.
Alternatively, you could use a second array that maps these field-names to the name you want to use in your code:
$map = array(
'm0' => 'm1'
);
echo 'M0: ', $row[$map['m0']];//use value of m0, which is the actual key if the $row array
Still, if you are hell-bound on unmaintainable, messy, error-prone and just awful code, you could use variable variables:
foreach ($row as $key => $value)
{
$$key = $val;
}
Note the double $ in $$key. This is like saying "the variable that is called whatever the value of $key is". If $key is firstname, the code above evaluates to $firstname = $value. But whatever you do: forget this is possible. It's like an enema: yes, it's possible, but you don't want one if you can avoid it. And in this case, you clearly can avoid it.
Loop through the $row var grabbing the key and value. If key starts with "m" followed by a 1 or 2 digit number, get the number, subtract one, concatenate it with "m", and assign the value. Otherwise just interpolate key into variable name and assign value.
foreach ( $row as $key => $value ) {
if ( preg_match('/^m(\d{1,2})/', $key, $matches) ) {
${'m' . ($matches[1] - 1)} = $value;
}
else { $$key = $value; }
}
In the above example, $row['m1'] value gets assigned to var $m0, and $row['firstPlace'] to var $firstPlace, etc.
I have this code above which i use to implode some variable.
The issue is that i need to create the same thing for $hostess_name[] as i did for $hostess_id_selected[].
I don't know what am i doing wrong.
I need to implode it the same way as i did with $hostess_id_selected1
foreach($hostess_id as $val) {
$hostess_id_selected[] = $val;
$sqlnomehostess="SELECT nome_hostess FROM hostess where id='$val'";
$resultnomehostess=mysql_query($sqlnomehostess)or die(mysql_error());
$hostess_name= array();
while ($row=mysql_fetch_array($resultnomehostess,MYSQL_ASSOC)) {
$hostess_name[] = $row['nome_hostess'];
}
}
$hostess_id_selected1 = implode("-",$hostess_id_selected);
you have $hostess_name= array(); inside the loop. move it above
EDIT:
some tips:
foreach($hostess_id as $val) {
$hostess_id_selected[] = $val;
// this is pointless, i mean - you are recreating $hostess_id
btw, just a little tip for improvement - instead of running many SQL queries you can use a single query:
$sql = "SELECT GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list
FROM `hostess`
WHERE id IN (".implode(',',$hostess_id).")";
if the items in $hostess_id are not necessarily numeric:
$sql_ids = array();
foreach($hostess_id as $id)
$sql_ids[] = mysql_real_escape_string($id);
$sql = "SELECT GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list
FROM `hostess`
WHERE id IN (".implode(',',$sql_ids).")";
and after that:
the sql query returns 1 row with a column called "name_list", which contains the names joined with "-".
if you want to maintain the order of the id and name - you should do:
$sql = "SELECT
GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list,
GROUP_CONTACT(`id` SEPARATOR '-') AS id_list
FROM `hostess`
WHERE id IN (".implode(',',$hostess_id).")";
implode is a basic function of php. It always work perfect.
Just check your array $hostess_id_selected, what it returning.
I think it will help you.
So my problem is this I got a code that loops trough a loggfile then compares them to a treestructure and then gives them a id that correspond to the id in the structure. To not get a lot of bad traffic i sort out all the 302 and above.
The problem is now that i want some specific 302s to count that have a particular pagetype in the structure. This is not a big problem as I can just match the url in the loggfile against the url in the tree structure but some loggfiles does not use friendly url while the structure is in friendly url this creates a problem but I can just match the id in the query parameter with the id in the structure. I then make a string of all the ids that match the special pagetype that I want.
The problem is this I can not get the Mysql statement to work, it looks like this.
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN '$check'";
A example query can look like this "id=4&epslanguage=sv" so I want to check only the id=X part.
It´s a kinda easy question really im just stuck and can not get it to work, any help is appreciated!
I think your Q is: How do I extract id from that part of a line?
".. so I want to check only the id=X part."
Once you have isolated that string then you can use:
$string = "id=4&abclang=sv";
parse_str($string);
echo $id; // 4
EDIT
In light of other responses:
$strings[] = "id=4&abclang=sv";
$strings[] = "id=45&abclang=en";
$vals = array();
foreach( $strings as $string){
parse_str($string);
$vals[] = $id ;
}
$in_clause = join(",", $vals) ;
$sql = "SELECT lid FROM logfile WHERE something IN ($in_clause) ";
echo $sql; // SELECT lid FROM logfile WHERE something IN (4,45)
So you have the IDs already and want to filter the MySQL query to just get these rows?
$check = Array(1, 2, 3, 4);
$check = implode(",", $check);
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN ($check)";
How do I find the first column with no data?
//column pet1='dog'
//column pet2=''
//column pet3=''
//column pet4='cat'
if($F=="getempty"){
$uid=$_GET["uid"];
$sql = mysql_query("SELECT DISTINCT pet1,pet2,pet3,pet4 FROM a WHERE uid='".$uid."' AND pet1='' OR pet2='' OR pet3=''OR pet4=''");
while($column=mysql_fetch_field($sql)){
$empty=$column->name;
echo json_encode(array("empty"=>$empty));
}
}else{}
I keep trying but so far it just returns all column names if one is empty
pet1,pet2,pet3,pet4
DISTINCT will combine the rows which are exactly alike (having all the selected columns the same) and return them.
To get the name of the first empty column, use a query like:
SELECT
CASE
WHEN pet1 = '' THEN 'pet1'
WHEN pet2 = '' THEN 'pet2'
WHEN pet3 = '' THEN 'pet3'
WHEN pet4 = '' THEN 'pet4'
ELSE NULL
END AS firstempty
FROM a
WHERE uid = '$uid';
The idea is that the CASE statement checks each one in order, and finding an empty one returns the column name without checking the rest of them.
Don't forget to escape $uid with mysql_real_escape_string() before passing it to the query.
$uid = mysql_real_escape_string($uid);
Since we're now getting the column name inside a field called firstempty, we'll also need to change the way it's fetched:
while($row = mysql_fetch_assoc($sql)){
$empty = $row['firstempty'];
echo json_encode(array("empty"=>$empty));
}
I have a HTML page where a user can select multiple values in a checklist. Depending on the number of items selected, that's how many times I would like to append a variable to itself, separated by commas (if that makes sense)
For example, if my string was $string = "'$apple'" (yes, my string is meant to be formatted this way, you'll see why) and the user selected 3 items from the checklist, my string would end up being:
"'$apple', '$apple', '$apple'"
When the user submits the page, here's the PHP:
$category = mysql_real_escape_string($_POST['category']);
$string = 'test';
if (count($category) === 1) {
//donothing
}
else{
$category = implode(",",$category);
}
$numcat = count($category); //count number of items in $category, save value to $numcat
$query = mysql_query("INSERT INTO table (". $category .") VALUES ('$string')");
For reference, if the user has selected "apple, banana, grape" from the HTML form, I want the query to essentially look like this:
$query = mysql_query("INSERT INTO table (apple, banana, grape) VALUES ('$string', '$string', '$string')");
Another example, if the user has selected just "apple, grape" from the HTML form, I want it to end up looking like this:
$query = mysql_query("INSERT INTO table (apple, grape) VALUES ('$string', '$string')");
The INSERT INTO table (apple, grape) is already solved by just doing INSERT INTO table (". $category .") since I have imploded it and seperated by commas, but then I also need the string to display 'X' amount of times in VALUES, depending on the result from count($category)?
How can I do this?
It looks to me that you want to take a variable and a count and make a string from it. If that is the case, will this work:
$value = "'x'";
$count = 3;
$a = array_fill(0, $count, $value);
$str = implode(',', $a);
Then, $str will contain "'x','x','x'".
You can ask why I didn't use str_repeat. I haven't seen a way to use a glue with that. The implode function lets me use , as the glue. I just needed to make it an array first.