PHP: Merge two MySql array result - php

i fetch id and name from categories table like this :
|id|name| tag |desc|order|status|
|1 |test| NULL|NULL| 1 | 1 |
$i = 0;
$allcats = Access::FETCH("SELECT * FROM " . CATS . "");
$cats = array();
foreach($allcats AS $row2){
$cats[$i] = array("name" => $row2['name'], "id" => $row2['id']);
$i++;
}
i fetch category id for each news :
|id|catid|storyid|
|1 | 1 | 5 |
$groupcats = Access::FETCH("SELECT * FROM " . GROUPCATS . " WHERE storyid = ?", $row['postid']);
Now, i need to print name of cat for storyid. i,e : i need to print test(catname) for story id 5.
How do can i print this?

Easier to do with with a join rather than in php. Something like,
$joinedcats = Access::FETCH("SELECT name FROM " . CATS .
" JOIN " . GROUPCATS . " ON catid = id");
foreach($joinedcats as $row) {
echo $row['name'];
}
See https://dev.mysql.com/doc/refman/5.5/en/join.html

You can use join to get needed rows for each story:
"SELECT * FROM " . GROUPCATS . " LEFT JOIN " . CATS . " USING(categoryid) WHERE storyid = ?"

Related

select different columns from multiple tables with common variable

I have three tables: - food - toys - animals
Each table has the columns - id, color, item
Table toys has additional columns - sn, date and more
Need to select all items from all tables with color = red and get them separately on client side
Something like:
$color = 'red';
$sql = "select * from food, toys, animals where color = :acolor";
$st = $db->prepare($sql);
$st->execute([":acolor" => $color]);
$food = $toys = $animals = '';
while($row = $st->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
$arr = [];
array_push($arr, $food, $toys, $animals);
echo json_encode($arr);
client side
...
data = JSON.parse(data);
$('#wrapfood').html(data[0]);
$('#wraptoys').html(data[1]);
$('#wrapanimals').html(data[2]);
As the final result:
wrapfood should have 5 divs with class food
wraptoys should have 9 divs with class toys
wrapanimals should have 21 divs with class animals
I tried various versions of the above code without success - getting errors on server side.
Any help?
You can use this
$data = array('food' => array(),'toys' => array(),'animals' => array());
$color = 'red';
$foodSql = "select * from food where color = :acolor";
$toySql = "select * from toys where color = :acolor";
$animalSql = "select * from animals where color = :acolor";
$ft = $db->prepare($foodSql);
$tt = $db->prepare($toySql);
$at = $db->prepare($animalSql);
$ft->execute([":acolor" => $color]);
$tt->execute([":acolor" => $color]);
$at->execute([":acolor" => $color]);
$food, $toys, $animals = '';
while($row = $ft->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
}
array_push($data['food'], $food);
while($row = $tt->fetch()){
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
array_push($data['toys'],$toys);
while($row = $at->fetch()){
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
array_push($data['animals'],$animals);
echo json_encode($data);
Then on client side you can access the data as
data = JSON.parse(data);
$('#wrapfood').html(data.food);
$('#wraptoys').html(data.toys);
$('#wrapanimals').html(data.animals);
if you want to use a single select statement here is the solution... if you just want a color item and id
SELECT f.* from food f
UNION
SELECT a.* from animals a
UNION
SELECT t.id, t.color,t.item from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
if you want sn and date also
SELECT f.*,null,null from food f
UNION
SELECT a.*,null,null from animals a
UNION
SELECT t.* from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
if your columns of the tales are in the same order as you specified id, color, and item then no problem with the above queries otherwise if the order is different arrange the column names in select statement accordingly...
now you can still use the above query if you want to separate it only client site in the single loop... just concatenate in the select statement.
here is what you can do...
SELECT CONCAT("#food",f.id), CONCAT("#food",f.color),CONCAT("#food",f.item),null,null from food f
UNION
SELECT CONCAT("#animals",a.id),CONCAT("#animals",a.color),CONCAT("#animals",a.item),null,null from animals a
UNION
SELECT CONCAT("#toys",t.id),CONCAT("#toys",t.color),CONCAT("#toys",t.item),CONCAT("#toys",t.sn),CONCAT("#toys",t.date) from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
now we have concatenated the names of the tables with the column now when we display it we can easily filter them with their names...
this is how you filter them later on...
if(substr( $row['id'], 0, 5 ) === "#food"){
echo substr($row['id'],4);
}

PHP SQL integration

I am connected to my database.
Created a drop down-box. Which works fine:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Now I am stuck trying to put the values from table Customer into an array
Which looks like this:
$types = array (
'A' => 10.99,
'B' => 4.99,
'C' => 13.99);
What I intend to do is to create this array where,
Instead of A B C, there are CustomeName and CustomerPrice in place of the price.
The Customer table has
+----------------+-----------------+---------------+
| Customer_ID | CustomerName | CustomerPrice |
+----------------+-----------------+---------------+
| 1 | A | 10.99 |
| 2 | B | 4.99 |
| 3 | C | 13.99 |
+----------------+-----------------+---------------+
Please help
You basically do the same thing you did with the drop down except to generate the array. You could do it in the same loop:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
$array = array();
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
$array[$row['CustomerName']] = $row['CustomerPrice'];
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Hope this helps

MYSQL field ID value changing

Databases:
listings
| ID | TITLE | COMPANY_ID |
| 1 | One | 1 |
| 2 | One | 1 |
| 3 | One | 1 |
Companies
| ID | NAME |
| 1 | One |
| 2 | Two |
| 3 | Three |
I have the PDO MYSQL statement:
"SELECT
listings.ID,
listings.TITLE,
listings.COMPANY_ID,
companies.ID,
companies.NAME
FROM listings INNER JOIN companies ON (listings.COMPANY_ID = companies.ID ) WHERE (listings.TITLE = :p1 AND companies.NAME = :p2 )LIMIT 10"
The associative array output:
Array
(
[ID] => 1
[TITLE] => analyst
[COMPANY_ID] => 1
[NAME] => one
)
Array
(
[ID] => 1
[TITLE] => analyst
[COMPANY_ID] => 1
[NAME] => one
)
Array
(
[ID] => 1
[TITLE] => analyst
[COMPANY_ID] => 1
[NAME] => one
)
When executing this query, my ID field that is being outputted to the PHP fetch associative array is being returned as 1.
With the exception to the ID, the output works as expected.
Why is my ID value changing?
______________________
METHOD:
protected function search_joined($parameters, $func){
$field = "*";
if(isset($parameters["fields"])){
if($parameters["fields"] != "*" && gettype($parameters["fields"]) == gettype(array())){
if(count($parameters["fields"]) == 2){
$field = "";
foreach($parameters["fields"] as $key=>$v){
foreach($v as $v_){
$field.= $parameters["tables"][$key] . "." . $v_ . ",";
}
}
$field = rtrim($field, ",");
}
}
}
$cond_ = "";
$values = array();
if(gettype($parameters["condArry"]) == gettype(array())){
$COND_TYPE = " AND ";
foreach($parameters["condArry"] as $v){
$operator = " = ";
if($v[1][0] == "%" || substr($v[1], -1) == "%"){
$operator=" LIKE ";
}
if(substr($v[1], 5) == "L::_>"){
$operator=" > ";
$v[1] = str_replace($v[1], "L::_>", "");
}
if($v[1][0] == "!"){
$operator=" != ";
//$v[1] = str_replace($v[1], "!", "");
$v[1] = substr($v[1], 1);
}
$COND_TYPE = (
(isset($v[2]))?
(
($v[2] == "&")? " AND " :
(
(($v[2]=="||")? " OR ": "")
)
): " AND "
);
$unique = md5($v[0] . $v[1]);
$cond_.= $v[0] . $operator . ":".substr($v[0], strpos($v[0], ".") + 1).$unique. " " . $COND_TYPE . " ";
$values[':'.substr($v[0], strpos($v[0], ".") + 1).$unique] = $v[1];
}
$cond_ = "WHERE (" . substr($cond_, 0, strlen($COND_TYPE)*(-1)) . ")";
}
//$cond_ = rtrim($cond_, ",");
$joiner = $parameters["tables"][0] . "." . $parameters["joiner"][0] . "=" . $parameters["tables"][1] . "." . $parameters["joiner"][1] . " ";
$sql = "SELECT ". $field . " FROM " . $parameters["tables"][0] . " INNER JOIN " . $parameters["tables"][1] . " ON (" . $joiner . ") " .$cond_ . (isset($parameters["LIMIT"])? "LIMIT " . $parameters["LIMIT"]: "");
echo $sql;
if(isset($parameters["test"])){
if($parameters["test"] == true){
echo "<br>". $sql . "<br>";
}
}
//echo "<br>". $sql . "<br>";
$q = $parameters["connection"]->prepare($sql);
foreach($values as $key => $v){
$q->bindvalue($key, $v);
echo "<br>" . $key . " : " . $v . "<br>";
}
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)) {
if(!$func($row)){
break;
}
}
$conTableArry = null;
}
CALLER:
$params_= array(
"connection"=>$this->connection_,
"tables"=>array("listings", "companies"),
"joiner"=>array("COMPANY_ID","ID"),
"fields"=> array(
array(
"ID",
"TITLE",
"PAYMIN",
"PAYMAX",
"GEO_LOCATIONS_ID",
"CRIMINAL_HISTORY_REQ",
"EVAL_EXAM_REQ",
"AGE_REQ",
"EX_REQ",
"DRIVERS_LICENSE_REQ",
"CERTIFICATE_REQ",
"EDUCATION_REQ",
"RESUME_REQ" ,
"POSITIONS",
"COMPANY_ID"
),
array(
"ID",
"NAME"
)
),
"condArry"=>array(array("listings.TITLE", "analyst"), array("companies.NAME", "suitespec")),
"LIMIT"=>$LIMIT,
);
parent::search_joined($params_, function($r){
out($r);
return true;
});
You've got some confusing syntax in your SQL
SELECT
listings.ID,
listings.TITLE,
listings.COMPANY_ID,
companies.ID,
companies.NAME
FROM listings
INNER JOIN companies ON (listings.COMPANY_ID = companies.ID )
WHERE (listings.TITLE = :p1 AND companies.NAME = :p2 )
LIMIT 10
You have two ID columns and no aliasing. So you're likely getting the second ID back. Try aliasing the second ID column and trying again
SELECT
listings.ID,
listings.TITLE,
listings.COMPANY_ID,
companies.ID AS comp_id,
companies.NAME
You should be able to solve this by using unique column names for your result set (you currently use ID twice).
Change your SQL to something like this:
"SELECT
listings.ID,
listings.TITLE,
listings.COMPANY_ID,
companies.ID AS CID,
companies.NAME
FROM listings
INNER JOIN companies ON (listings.COMPANY_ID = companies.ID )
WHERE (listings.TITLE = :p1
AND companies.NAME = :p2 )LIMIT 10"
Notice the 5th line of that. I've changed it from companies.ID to companies.ID AS CID.

access values after comma separator from single field of mysql (Codeigniter)

I have one problem while retrieveing value from mysql using codeigniter.
I have one table name task and in that there is one field of assigneduserid.
Table - Task:
id | title | Title | assigneduserid
--------------------------------------------------------
1 | Workspace |PMS | 23,21
Table - User
id | title
-----------------
23 | Ashish
21 | Ritesh
In assigneduserid field there are two values in that field that is 23,21.
I want to display task title in both user login.
but it displays only to Ashish login.
how can i solve it??
Following is my model:-
function getTask($id, $is_master_admin) {
$this->db->select('task.*, workspace.title as workspacetitle, user.title as usertitle');
$this->db->join(WORKSPACE, WORKSPACE . '.id = ' . TASK . '.workspaceid', 'inner');
$this->db->join(USER, USER . '.id = ' . TASK . '.userid', 'inner');
$this->db->from(TASK);
$this->db->group_by('task.id');
if (!$is_master_admin) {
$this->db->where(USER . '.id', $id);
}
$this->db->where(TASK . '.tasktypeid', '1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Can any one please help??
function getTask($id, $is_master_admin) {
$data= $this->db->group_by('task.id')->get('task')->result();//check what value your getting in data and then use foreach and select the user from the user table
foreach($data as $value):
$array= $this->db->where('id',$value->id)->get('user')->result();
endforeach;
}
Try, Haven't checked it,
$tsql = " SELECT task.*, workspace.title AS workspacetitle, GROUP_CONCAT(user.title ORDER BY id) AS usertitle ".
" INNER JOIN ". WORKSPACE ." ON ". WORKSPACE .".id = " . TASK . ".workspaceid ".
" INNER JOIN USER ON FIND_IN_SET(".USER . ".id, ". TASK .".assigneduserid ) > 0 ".
" FROM ". TASK ;
if (!$is_master_admin) {
$tsql .= " WHERE ". USER . ".id =". $id;
}
$tsql .= " WHERE ". TASK . ".tasktypeid =1 ";
$tsql .= " GROUP BY ". TASK .".id ";
$query = $this->db->query($tsql);

How do I change a URL category number to a word with PHP and MySQL?

I bought an iPhone wallpaper gallery PHP script a year ago, and it has been running great. I've been slowly learning PHP and MySQL by doing little tweaks here and there.
To view a category, the URL is www.example.com/index.php?catid=27, and I want to change it to www.example.com/index.php?catid=apple for SEO reasons. I know I can futher tidy up the URL with .htaccess but I just want to get this word slug to begin with.
This is the code (inside index.php) that I think generates the category pages:
if (($_REQUEST['catid']) && ($_REQUEST['catid'] > 1)) {
$catid = $_REQUEST['catid'];
if (is_numeric($catid)) {
$tempitemarray = $myitems->getItemsByCategory($catid);
$catnav = "&catid=" . $catid;
$tempcat = new Category();
$tempcat->getCategory($catid);
$maintitle = "<h1>" . $tempcat->getCategoryName() . " " . $itemplural . "</h1>";
}
That code calls another PHP page called itemList.php, and inside that page I found this code:
public function getItemsByCategory($catid) {
$this->retrieveSQL = "select * from items i, item_category_lookup l where livedate < '" . $this->currentdate . "' and i.active = " . $this->showApproved . " and l.categoryid = $catid and i.id = l.itemid order by i.livedate desc limit " . $this->startRow . "," . $this->numRows;
$this->countSQL = "select * from items i, item_category_lookup l where livedate < '" . $this->currentdate . "' and i.active = " . $this->showApproved . " and l.categoryid = $catid and i.id = l.itemid";
$this->retrieveItems();
return $this->items;
}
This is the 'items' table:
id | itemname | itemdec | itemkeywords | createdate | viewcount | active | rating | livedate | sourcedesc | sourceurl
-----------------------------------
64 | Apple Logo
This is the 'item_category_lookup' table:
categoryid | itemid
-------------------------
27 | 64
This is the 'category' table below. It's not called in the query above but does have the actual category names. How would I implement it?
id | categoryid
------------------
27 | Apple
You might change the SQL of $this->retrieveSQL = ... into
if (!is_number($catid)) {
$this->retrieveSQL = "select * from items i, item_category_lookup l, category j where livedate < '" . $this->currentdate . "' and i.active = " . $this->showApproved . " and i.id = l.itemid and j.id = l.categroyid and j.categoryid = "$catid" order by i.livedate desc limit " . $this->startRow . "," . $this->numRows;
}
Try this:
URL example: www.example.com/index.php?catid=27-apple
if ( isset( $_REQUEST['catid'] ) ) {
$catSEO = explode( '-', $_REQUEST['catid'] );
}
$catid = is_numeric( $catSEO[0] ) ? $catSEO:0;

Categories