I am trying to run a query to determine if a column A is true. If its true, get the contents of a different column B (possible array separated by ",") and use those contents to query a different table. My problem is, column B may be one number or may be 10 numbers all separated by "," and I need to query the second table for a column for each of the numbers of the previous query. If someone can help that would be great.
edit: I tried to use the array explode function but can't figure out how to query the next table to include those values.
I picture it being something like
query = select * from table where location = arrayValue[1] or location = arrayValue[2]
Adaptation of Telmo Marques here but improved :
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
array_walk($bcolumnArray, 'htmlentities');
//Build SQL query
$SQL = 'SELECT * FROM table';
if(count($bcolumnArray)){
$SQL.= ' WHERE IN ("'.implode('", "', $vbcolumnArray).'")';
}
//Query your second table here
$Qry = mysql_query($sql);
// Results here :
while($Res = mysql_fetch_assoc($Qry)){
print_r($Res);
}
?>
I would suggest PDO also... take a look : PDO.
Use PHP's explode() function to transform your string into an array.
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
//Build SQL query
$sql = "SELECT * FROM table WHERE ";
for($i=0; $i < count($bcolumnArray); $i++)
{
$sql .= "location = " . $value;
if($i != count($bcolumnArray)-1)
{
$sql .= " or ";
}
}
//Query your second table here
mysql_query($sql);
?>
Documentation: http://php.net/manual/en/function.explode.php
Related
I have a DB wherein one table, the column has a list of words separated by the comma, which has to be compared and select accordingly. but in PHP so far I have written SQL code for one word in a column cell-like,
<?PHP
$sql2 = "SELECT * FROM table WHERE name = 'name'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
?>
but here, I have a list of words in the name column separated by a column.
how do I write code to extract all those words into single and check each one of them with the user input text?
Hope I m clear, Any help is appreciated..
Use filter_input() for Input,
use explode() for Input,
use SQL IN or SQL REGEX with and/or for SQL Part.
$clean_userinput = filter_input(INPUT_GET, "userinput", FILTER_SANITIZE_STRING);
like $_GET["userinput"]
$array_userinput = explode(" ", $clean_userinput);
$in = "(";
for($i=0;$i <count($array_userinput); $i++) {
$in .= "'" . trim($array_userinput[$i]) . "'";
}
$in .= ")"
$sql2 = "SELECT * FROM table WHERE name IN ". $in;
That all magic simple. php.net is your best source.
I am trying to get the column names and field values from a table for ONE record. If a column name was 'sellers' and the field value was 'Bob', the desired output would be: seller Bob
The output will actually be used for a script like this:
$fields['sellers']->setValue($sellers);
Where 'sellers' is the column name and $sellers is the field value.
There are dozens of columns in the table.
The script below only outputs the column names - not the field values.
Any help is appreciated.
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
$sql_result = mysqli_query($db, $sql);
for($i = 0; $i < mysqli_num_fields($sql_result); $i++) {
$field_info = mysqli_fetch_field($sql_result);
$col = "{$field_info->name}";
echo $col . ' ';
while ($row = mysqli_fetch_array($sql_result)) {
$data = $row[$col];
echo $data."<br>";
}
}
Not sure if I exactly understand what you're trying to do but would using mysqli_fetch_assoc() and a foreach loop give your desired result?
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
$sql_result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($sql_result);
foreach($row as $column => $value) {
echo $column . " " . $value;
}
You should just call mysqli_fetch_array() once, not in a loop for each column. Because every time you call it, it moves to the next row of results, it doesn't re-fetch the old row. Since you only have one row of results, the repeated calls just return false.
$row = mysqli_fetch_array($sql_result);
for($i = 0; $i < mysqli_num_fields($sql_result); $i++) {
$field_info = mysqli_fetch_field($sql_result);
$col = "{$field_info->name}";
echo $col . ' ' . $row[$col];
}
But there isn't really any need to use mysqli_fetch_field() to get the field names. Since $row is an associative array, the field names are just the keys of the array. However, it would be better to use mysqli_fetch_assoc(), because mysqli_fetch_array() returns an array that contains both named and numbered elements; mysqli_fetch_assoc() just returns the named elements. So the answer by WheatBeak is how most would do what you want.
I think that there's a problem with the interpolation.
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
Using variables between apostrophes sends the string "$trans_id" in the SQL query instead of the value which $trans_id contains. Try this:
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '" . $trans_id . "' ";
I have a table that contains information such as names, email-addresses, numbers etc.
Let's pretend that I have 30 contacts by the same name but they all live in different cities . How do I split the comma and replace it with and ....
Example
SELECT * WHERE name %$searchString% OR city %$searchString%...
Now if $searchString contains comma
SELECT * WHERE name %$searchString% OR city %$searchString%... AND SELECT * WHERE name %$searchString2% OR city %$searchString2%...
The $searchString2 contains information that's separated with comma.
Update
I want to search each row over and over again as many times as commas exist.
I'm sorry that I can't explain myself
This depends on whether you want to return rows where name or city match the search values exactly (=), or rows where any part of name or city match the search values (LIKE).
Regardless of which one you need, you can start out by converting your search string into an array of strings like this:
$strings = array_map('trim', explode(',', $searchString));
The array_map('trim'... ensures that you don't try to match any spaces before or after the commas in your comma-separated search string.
Here are examples for how to execute your query using prepared statements in PDO. First, full matches using IN:
$phs = rtrim(str_repeat('?,', count($strings)),',');
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE name IN ($phs) OR city IN ($phs)");
// double the string values to us in both INs
$values = array_merge($strings, $strings);
$stmt->execute($values);
and partial matches using LIKE:
$sql = '';
foreach ($strings as $string) {
$sql .= ' name LIKE ? OR city LIKE ? OR';
$values[] = $string;
$values[] = $string;
}
$stmt = $pdo->prepare('SELECT * FROM your_table WHERE' . rtrim($sql, ' OR'));
$stmt->execute($values);
You need to use WHERE IN in SQL statement.
SELECT * WHERE name LIKE '%$searchString%' AND city IN ('city1', 'city2', 'city3'...)
Here is the good discussion on how to do it in PHP: Passing an array to a query using a WHERE clause
Something like this?
You will need to escape/clean the value of searchString.
<?php
// $searchString = "Cardiff,London,New York";
$SQL = 'SELECT * FROM table WHERE ';
$searchStrings = explode(',',$searchString);
$SQLArray = array();
foreach($searchStrings as $searchString) {
$SQLArray[] = "name LIKE '%$searchString%'";
$SQLArray[] = "city LIKE '%$searchString%'";
}
$SQL .= implode(' OR ',$SQLArray);
// print $SQL;
?>
I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.
I have this portion of code and it gives me the error in the title.
I have a count $k from 1 to 5 for each table.
$myarray consists of at least 3 to 4 names.
The error occurs in the line with $qu .= ...
What i tried so far: changing the variablename $i to $v{$i} in the $qu .= line.
So is there any possibility to iterate the query? So that it has as many ANDs in the WHERE clause as the count of the array is?
while ($k<=5) {
$queryname = "SELECT Name FROM description";
$qname = mysql_query($queryname,$link);
while ($reihe = mysql_fetch_object($qname)) {
{
$unse = unserialize($reihe->Name);
{
foreach ($unse as $j=>$h)
foreach ($h as $m) {
$myarray = preg_split('/ |\s| /',$m);
{
echo "<br>";
$array_empty = $myarray;
$empty_elements = array("");
$myarray = array_diff($array_empty,$empty_elements);
var_dump($myarray);
for ($i=1; $i<=count($myarray); $i++) {
$v{$i} = $myarray[$i];
echo $v{$i};
$esc{$i} = strtolower(mysql_escape_string($v{$i}));
echo "<br>" . $esc{$i} . "<br>";
$qu = "SELECT * FROM `table ID=$k` WHERE";
$qu{$i} .= "AND `table ID=$k`.`name` LIKE '%$esc{$i}%'";
}
}
}
{
$test_a = mysql_query($qu,$link) or die (mysql_error());
echo "<br>";
var_dump($test_a);
for ($x=0; $x<mysql_num_rows($test_a); $x++) {
$row = mysql_result($test_a,$x,'data1');
$namee = mysql_result($test_a,$x,'data2');
echo 'data1' . $row . '<br>';
echo 'data2' . $namee . '<br>';
}
}
}
}
}
$k++;
}
You appear to have misunderstood some basic PHP syntax.
As mentioned in the manual:
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.
Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.
Therefore your use of curly braces throughout your code (except for those defining the scope of the for control structure) are wholly erroneous and do not accomplish what you intend.
Secondly, from your code it appears that you are storing relational data in serialised PHP objects; this defeats many of the benefits of using an RDBMS like MySQL. Unless you have compelling reasons for doing otherwise, you should probably store your PHP objects in a normalised form. For example, rather than each description record having a Name field that contains a serialised PHP object whose properties are arrays that hold imploded strings of names, just store each such name in a new descriptionNames table that references the related record in the description table:
CREATE TABLE descriptionNames (
descriptionID INT NOT NULL,
name VARCHAR(50),
PRIMARY KEY (descriptionId, name),
FOREIGN KEY (descriptionId) REFERENCES description (descriptionId)
);
It also appears that you have five (schematically) identical tables named Table ID=1, Table ID=2, etc.? If so, you should probably combine your five tables into one, with a column (if so desired) to indicate from which table the record originated; I would also suggest changing your table names so that they avoid using special characters like whitespace and = as they will likely only cause trouble and confusion further down the road if you forget to properly quote them. For example:
ALTER TABLE `Table ID=1`
RENAME TO CombiTable,
ADD COLUMN FromTableID TINYINT NOT NULL;
UPDATE CombiTable SET FromTableID = 1;
INSERT INTO CombiTable
SELECT *, 2 FROM `Table ID=2` UNION ALL
SELECT *, 3 FROM `Table ID=3` UNION ALL
SELECT *, 4 FROM `Table ID=4` UNION ALL
SELECT *, 5 FROM `Table ID=5`;
SELECT * FROM CombiTable; -- check everything is okay
DROP TABLE `Table ID=2`, `Table ID=3`, `Table ID=4`, `Table ID=5`;
In any event, you shouldn't use the ancient mysql_* functions. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either the PDO abstraction layer or else the improved MySQLi extension.
If you need to maintain your existing data structure, with PDO you could do something like:
$dbh = new PDO("mysql:dbname=$dbname;charset=utf8", $user, $password);
$qry = $dbh->query("SELECT Name FROM description");
$myarray = array();
while ($reihe = $dbh->fetchColumn())
foreach (unserialize($reihe) as $h)
foreach ($h as $m)
array_merge($myarray, preg_split("/\s+/", $m, -1, PREG_SPLIT_NO_EMPTY));
for ($k = 1; $k <= 5; $k++) {
$qry = $dbh->prepare("SELECT * FROM `table ID=$k` WHERE " . implode(" OR ",
array_pad(array(), count($myarray), "name LIKE CONCAT('%', ?, '%')")
));
$qry->execute($myarray);
while($row = $qry->fetch()) {
echo "data1:$row[data1]<br/>";
echo "data2:$row[data2]<br/>";
}
}
However, using my proposed new data structure, you would only need do:
$dbh = new PDO("mysql:dbname=$dbname;charset=utf8", $user, $password);
$qry = $dbh->query("
SELECT *
FROM CombiTable JOIN descriptionNames USING (name)
WHERE FromTableID BETWEEN 1 AND 5 -- in case you have others?
ORDER BY FromTableID
");
while ($row = $qry->fetch()) {
echo "data1:$row[data1]<br/>";
echo "data2:$row[data2]<br/>";
}