SQL writing format - php

I would like to inner join to tables with sql like this:
$check_unscored = "select * from [user]
INNER JOIN [tenderrc]
on [user].[id] = [tenderrc].[userid]";
$result_unscored = mssql_query($check_unscored, $s);
while ($record_unscored = mssql_fetch_array($result_unscored))
{
$id = $record_unscored['id'];
$name = $record_unscored['name'];
$userid = $record_unscored['userid'];
$touser = $record_unscored['touser'];
$id = $record_unscored['id'];
$username = $record_unscored['username'];
$password = $record_unscored['password'];
}
I observed that a key name column called "id" exists in both table, and therefore $id = $record_unscored['id']; would be overwritten;
I tried $id = $record_unscored['user.id']; but it's not working! Actually how shall I specify the table name as well?

Use aliases:
$check_unscored = "
SELECT
u.id
, u.name
, u.userid
, u.touser
, t.id AS tender_id --- column alias
--- to remove duplicate names
, t.username
, t.password
FROM [user] AS u --- table alias her
INNER JOIN [tenderrc] AS t --- and here
ON u.[id] = t.[userid]
";

you could create a alias field etc
if you wont id from user you could use something like this
select [user].[id] as 'userid', [tenderrc].[*] from ...
I come from mySql world but i think its managable this way
and later access it this way
$id = $record_unscored['userid'];

You could do this using this function
http://hu2.php.net/manual/en/function.mssql-fetch-field.php
which can provide "column_source - the table from which the column was taken".
Example code:
$result = mssql_query("....");
$check_unscored = "
SELECT *
FROM [user]
INNER JOIN [tenderrc] ON [user].[id] = [tenderrc].[userid]";
$rows = fetch_multitable( mssql_query( $check_unscored, $s ));
foreach( $rows as $row ){
echo $row->user['id'];
echo $row->tenderrc['id'];
}
function fetch_multitable( $result ){
$fields = mssql_num_fields( $result );
$infos = array();
for( $i=0; $i < $fields; $i++ ){
$fieldinfo = mssql_fetch_field( $r, $i );
$infos[ $i ] = (object)array(
'table'=> $fieldinfo -> column_source
,'name' => $fieldinfo -> name
);
}
$rows = array();
while( $raw = mssql_fetch_row( $r )){
$row = array();
foreach( $raw as $i => $v ){
$info = $infos[ $i ];
$row[ $inf->table ][ $inf->name ] = $v;
}
$rows[] = (object)$row;
}
return $rows;
}

Related

bootstrap-treeview multilevel & three tables

First post here, so please bear with me.
I'm trying to create a treeview using bootstrap-treeview and I've nearly got my response page working but level 3 isn't, I can't get the next node working.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include "db_mysqli.php";
$result = mysqli_query($connection, "SELECT group_id, group_name FROM material_groups;");
$json_response = array(); //Create an array
while ($row = mysqli_fetch_array($result))
{
// GROUPs
$row_array = array();
$row_array['id'] = $row['group_id'];
$row_array['text'] = $row['group_name'];
$row_array['name'] = $row['group_name'];
$row_array['parent_id'] = $row['group_id'];
// $row_array['answers'] = array();
$group_id = $row['group_id'];
// MATERIAL TYPES
$type_qry = mysqli_query($connection, "SELECT material_types.material_type_id, material_groups.group_id, material_types.material_type_name FROM material_groups
INNER JOIN material_types ON material_groups.group_id = material_types.group_id
WHERE material_groups.group_id = ".$group_id."
ORDER BY material_types.material_type_id");
while ($type_row = mysqli_fetch_array($type_qry))
{
$row_array['nodes'][] = array(
// $itemsByReference[$item['id']]['nodes'] = array();
'id' => $type_row['material_type_id'],
'text' => $type_row['material_type_name'],
'name' => $type_row['material_type_name'],
'parent_id' => $type_row['group_id'],
);
$material_type_id = $type_row['material_type_id'];
// MATERIALS
$material_qry = mysqli_query($connection, "SELECT material_types.material_type_id, material_groups.group_id, materials.material_name, materials.material_id
FROM material_types INNER JOIN materials ON material_types.material_type_id = materials.material_type_id
INNER JOIN material_groups ON material_types.group_id = material_groups.group_id And materials.group_id = material_groups.group_id
WHERE material_types.material_type_id = ".$material_type_id." AND material_groups.group_id =".$group_id);
while ($material_row = mysqli_fetch_array($material_qry))
{
$row_array['nodes'][] = array(
'id' => $material_row['material_id'],
'text' => $material_row['material_name'],
'parent_id' => $material_row['material_type_id']
);
$mateial_id = $material_row['material_id'];
}
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
?>
Levels 1 and 2 work perfectly, any help would be greatly appreciated.
Thanks
I've tried a lot of different code but this was the closest to a working solution.

Echo out one value from an array

I selected an array of product IDs and product names from the table product. I tried to echo out only one product name from the array, but all I got was the first letter of the product name. Below is my code. Thanks in advance for any tips.
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
while ($userinfo1 = $info1->fetchobject()) {
$productid = "$userinfo1->productid";
$productname = "$userinfo1->productname";
}
echo $productname[0];
Add brackets to the variables inside the while loop to create the array
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
}
echo $productname[0];//this will print the first productname
I think is better make just 1 array of objects
$array=array();
while ($userinfo1 = $info1->fetchobject()) {
$array[] = $userinfo1;
}
echo $array[0]->productname;
instead of doing this :
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
while ($userinfo1 = $info1->fetchobject()) {
$productid = "$userinfo1->productid";
$productname = "$userinfo1->productname";
}
echo $productname[0];
Do this :
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
$counter =0;
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
echo $productid[counter];
echo $productname[counter];
counter++;
}
this way you'll echo out every value of the array
You have various options at your disposal. Take your look for instance, you could create an associative array like the following:
$items = array();
while ($userinfo1 = $info1->fetchobject()) {
$item = array(
'productid' => $userinfo1->$productid,
'productname' => $userinfo1->$productname
);
array_push($items, $item);
// or you could use native
// $uitems[] = $item;
}
That would give you an array ($users) that you could loop through and fetch for set index:
foreach($items as $item) {
print_r($item); // prints the whole user item.
//print $item['productid']; /* or even print the users product id.*/
}
Or simple for one item like you requested:
echo $items[0]['productid'];
Alternatively: if you'd like seperate arrays, you could do as stated in the other answers:
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
}

Create a php array with keys and values from mysql query

I'm trying to store my mysql query in an array like this :
$arr = array ( "field1"=>"value" , "field2"=>"value" , "field3"=>"value" , ... );
I've tried this but don't work like I need :
$row_selectProduct = array();
$sResult = $db->query( 'SELECT * FROM tbl' )
while ( $aRow = $sResult->fetch_assoc() )
{
$sInfo = $sResult->fetch_field();
// General output
$row_selectProduct[ $sInfo->name ] = $aRow;
}
$sResult->close();
Thx for help
EDIT :
Sorry for misunderstanding...
I'd like to name keys by the field name in database.
I try to reproduce this :
$result = array();
while ($row_selectProduct = mysql_fetch_assoc($selectProduct));
{
$row_array= array();
$row_array['field_name1_In_DB'] = $row_selectProduct['field_name1_In_DB'];
$row_array['field_name2_In_DB'] = $row_selectProduct['field_name2_In_DB'];
$row_array['field_name3_In_DB'] = $row_selectProduct['field_name3_In_DB'];
$row_array['field_name4_In_DB'] = $row_selectProduct['field_name4_In_DB'];
$row_array['field_name5_In_DB'] = $row_selectProduct['field_name5_In_DB'];
...
array_push($result,$row_array);
};
Using PDO connection functions, it's quite simple --
foreach($db->query('SELECT field_name1,field_name2 FROM table') as $row) {
echo $row['field_name1'].' '.$row['field_name2']; //etc...
}
Here's a good tutorial for PDO in PHP if you want more.
while ( $aRow = $sResult->fetch_assoc() )
{
foreach($aRow as $fieldname => $fieldvalue) {
$row_selectProduct[$fieldname] = $fieldvalue;
}
}
but you will overwrite your $row_selectedProduct with every record and the var at the end will only have stored the last record
if you would like to have all results in one array you should:
$results = array();
while ( $aRow = $sResult->fetch_assoc() )
{
$results[] = $aRow;
}
if you know that there will be only one result you need only:
$result = $sResult->fetch_assoc();

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

Dynamic Content in PHP array

This should be a quick one.
I'm pulling a list of id's and I need to place them in an array.
Here is my php code to get the list of id's
$get_archives = mysql_query("SELECT * FROM archive WHERE user = '$email' ");
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id = $row['insta_id'];
$insta_id = "'" . $insta_id."',";
echo $insta_id;
};
This echo's a list of id's that looks like this: '146176036','136514942',
Now I want to put that list into an array. So i tried something like this:
$y = array($insta_id);
However that isn't working. Any suggestions?
$y = array();
while ($row = mysql_fetch_assoc($get_archives)) {
$y[] = $row['insta_id'];
}
$myArray = array();
$get_archives = mysql_query("SELECT * FROM archive WHERE user = '$email' ");
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id = $row['insta_id'];
$insta_id = "'" . $insta_id."',";
$myArray[] =$insta_id;
};
did you mean like this: ?
$insta_id=array();
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id[] = $row['insta_id'];
}
Create an array, and push the values into it:
$values = array();
while ( $row = mysql_fetch_assoc( $get_archives ) ) {
array_push( $values, $row['insta_id'] );
}

Categories