I am working on an Asset Database problem using PHP / MySQL.
In this script I would like to search my assets by an asset id and have it return all related fields.
First I query the database asset table and find the asset's type. Then depending on the type I run 1 of 3 queries.
<?php
//make database connect
mysql_connect("localhost", "asset_db", "asset_db") or die(mysql_error());
mysql_select_db("asset_db") or die(mysql_error());
//get type of asset
$type = mysql_query("
SELECT asset.type
From asset
WHERE asset.id = 93120
")
or die(mysql_error());
switch ($type){
case "Server":
//do some stuff that involves a mysql query
mysql_query("
SELECT asset.id
,asset.company
,asset.location
,asset.purchase_date
,asset.purchase_order
,asset.value
,asset.type
,asset.notes
,server.manufacturer
,server.model
,server.serial_number
,server.esc
,server.user
,server.prev_user
,server.warranty
FROM asset
LEFT JOIN server
ON server.id = asset.id
WHERE asset.id = 93120
");
break;
case "Laptop":
//do some stuff that involves a mysql query
mysql_query("
SELECT asset.id
,asset.company
,asset.location
,asset.purchase_date
,asset.purchase_order
,asset.value
,asset.type
,asset.notes
,laptop.manufacturer
,laptop.model
,laptop.serial_number
,laptop.esc
,laptop.user
,laptop.prev_user
,laptop.warranty
FROM asset
LEFT JOIN laptop
ON laptop.id = asset.id
WHERE asset.id = 93120
");
break;
case "Desktop":
//do some stuff that involves a mysql query
mysql_query("
SELECT asset.id
,asset.company
,asset.location
,asset.purchase_date
,asset.purchase_order
,asset.value
,asset.type
,asset.notes
,desktop.manufacturer
,desktop.model
,desktop.serial_number
,desktop.esc
,desktop.user
,desktop.prev_user
,desktop.warranty
FROM asset
LEFT JOIN desktop
ON desktop.id = asset.id
WHERE asset.id = 93120
");
break;
}
?>
So far I am able to get asset.type into $type. How would I go about getting the rest of the variables (laptop.model to $model, asset.notes to $notes and so on)?
Thank you.
$sql = "YOUR QUERY";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
echo 'Start Record<br />';
echo $row['type'].'<br />';
echo $row['company'].'<br />';
echo $row['location'].'<br />';
echo 'End Record<br /> <br />';
}
Try that out to see what you get then you can use data as you wish;
You may also want to look at mysql_fetch_array, mysql_fetch_row or mysql_fetch_object. Choose which best suits your needs.
What you're doing will not work:
$type = mysql_query("
SELECT asset.type
From asset
WHERE asset.id = 93120
")
This puts a resultset into $type, not the type itself.
After you do that, you need to fetch a row, then fetch the field:
$result = mysql_query("
SELECT asset.type
From asset
WHERE asset.id = 93120
")
if($row = mysql_fetch_object($result)){
$type = $row->type;
// NOW you have the type in $type. Do something similar with the rest of the queries.
}
I guess you would want to do something like this:
$result = mysql_query($query);
$i = array();
while ($data = mysql_fetch_assoc($result)) {
$i[] = $data;
}
This would make $i a multidimensional array containing all of your query data and you could use it by doing the following
foreach ($i as $key => $value) {
echo $value['model'];
echo $value['serial'];
etc......
}
Please see:
http://us2.php.net/manual/en/mysql.examples-basic.php
http://us2.php.net/manual/en/function.mysql-query.php
You may take a look at http://php.net/manual/en/function.mysql-query.php.
A mysql_query returns a resource which contains the results of your query. This resource can be read out the following way:
$sql_result = mysql_query( [here your stuff] );
while ($row = mysql_fetch_assoc($sql_result)){
echo $row['model']; // prints the model
}
So, you have to loop through the result and traverse each row. row then is an associative array containing the single fields.
Hope this helps.
it must be just one table computers
so your code would be just:
<?php
//make database connect
mysql_connect("localhost", "asset_db", "asset_db") or die(mysql_error());
mysql_select_db("asset_db") or die(mysql_error());
$sql = "SELECT a.id, a.company, a.location, a.purchase_date, a.purchase_order,
a.value, a.type, a.notes, c.manufacturer, c.model,
c.serial_number, c.esc, c.user, c.prev_user, c.warranty
FROM asset a
LEFT JOIN computers c
ON c.id = a.id
WHERE a.id = 93120";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$data=array();
while($row = mysql_fetch_assoc($res)) $data[] = $row;
// now $data array contains all the rows returned
?>
Every time you see doubled code, y know you're doing something wrong.
Related
I'm starting to learn php. I'm able to extract the list of CD from the SQL query in [in this table][1] but there's another query which contains the Category which is linked via ID in this table.
How do I get all the columns in the same result set using one query?
<?php
include 'database_conn.php';
$sql = "SELECT id, title, year, price FROM table_cd";
$queryresult = mysqli_query($conn, $sql)
or die (mysqli_error($conn));
while($row = mysqli_fetch_assoc($queryresult)) {
$iid = $row['id'];
$title = $row['title'];
$year = $row['year'];
$price = $row['price'];
echo "<div>
$title
</div>\n";
echo $row['year'];
echo $row['price'];
}
?>
editCDForm.php:
<?php
$code = $_GET['itemCode'];
$sql = "SELECT * FROM table_cd WHERE table_category.ID = $code
JOIN table_category ON (table_category.Desc = table_cd.ID)";
?>
What you're looking for is called a JOIN which allows you to merge the rows from two or more tables into the same result set.
You can modify your query as illustrated below, by using a LEFT JOIN of the nmc_cd table and the nmc_category table on the catID column, as the common primary attribute between them, giving you the desired result set...
$sql = "SELECT nmc_cd.CDID, nmc_cd.CDTitle, nmc_cd.CDYear,
nmc_cd.CDPrice, nmc_category.catDesc
FROM nmc_cd
JOIN nmc_category on nmc_cd.catID = nmc_cd.catID";
Here's a nice article that may help you visualize what a JOIN looks like in your SQL.
Syntax for joins:
SELECT * FROM table1
JOIN table2 ON (table2.colunmname = table1.columnname)
use can get the data from both tables when joining them:
$sql = "SELECT FT.CDID, FT.CDTitle, FT.CDYear, FT.CDPrice,
ST.catDesc FROM nmc_cd AS FT LEFT JOIN nmc_category as ST ON
FT.catID=ST.catID";
I want to retrieve data from multiple tables using dot operator/join where arguments are passed from an HTML/PHP form.
HTML CODE
<input name="rollno" type="text" placeholder="Roll Number" required>
<input name="submit_view_details" type="submit" value="Proceed">
PHP CODE
if(isset($_POST['submit_view_details']))
{
$rollno = (int) $_POST['rollno'];
$query = "select * from table1, table2 where table1.{$rollno}=table2.{$rollno}";
$result=mysqli_query($connection,$query);
}
In the browser if enter the input 1 and echo this query then it looks like follows:
select * from table1, table2 where table1.1=table2.1
and no row is fetched despite of having data in the table(s).
it only works if the query looks like follows:
select * from table1,table2 where table1.rollno=table2.rollno
However, in that case it fetches all the rows but I need only the row of the rollno that user entered in the above mentioned form.
I am just not able to work this out. Help would be much appreciated. Thanks!
Use the AND keyword to specify the rollno.
SELECT * FROM table1, table2 WHERE table1.rollno = table2.rollno
AND table1.rollno = {$rollno};
You could probably use the keyword JOIN instead like this :
SELECT * FROM table1 NATURAL JOIN table2
WHERE rollno = {$rollno};
You need joins
take a reference of joins from here,
i am sure it will help
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
You should use join like this
$query = "SELECT tbl1.*, tbl2.*
FROM tbl1
INNER JOIN tbl2 ON tbl1.id = tbl2.id
WHERE tbl1.column = value ";
foreach ($pieces_2 AS $value) {
$pieces_3[] ="(CONCAT_WS('|',$presql2) like '%$value%')"; //concat all columns from one table
}
$serch_jyouken = implode(" and ",$pieces_3); // for multiple keywords
$result1 = mysqli_query($connection, "select p.p_no from pfr_data p where (" .$serch_jyouken .")");
$res1 = array();
while($r1 = mysqli_fetch_array($result1){
$res1[] = $r1['p_no'] ; //fetch primary key from table and store it into array
}
foreach ($pieces_2 AS $value) {
$pieces_4[] ="(CONCAT_WS('|',$presql3) like '%$value%')"; // same as above
}
$serch_jyouken1 = implode(" and ",$pieces_4);
$result2 = mysqli_query($connection, "select p2.p_no from pfr_mod_inform p2 where (" .$serch_jyouken1 .")" );
$res2 = array();
while($r2 = mysqli_fetch_array($result2)){
$res2[] = $r2['p_no'];
}
$res_mrg = array_merge($res1 , $res2); //merge array
$result = implode("','",$res_mrg ); // array to sring
$sql5 = $presql ." from pfr_data p where p.p_no in ('$result') order by p.section_p,p.status,p.no";
Hi i have a small problem with the execution of query using if else condition.
I have 2 tables i.e dashboard_widget and dashboard_widget_users and in both this table i store my unserialize configuration.Users will always get the configuration from dashboard_widget_users table.But if the configuration is Null then it will take bydefault configuration from dashboard_widget table.I just want to use if else condition and i tried to do so but unable to execute it properly.The condition for if(!empty($empty_config)) is getting satisfied but if it empty then i am not getting any result.Thank you.
dashboard_widget_users table
dashboard_widget table
Here is my php code:
$query = "SELECT dashboard_widget_users.configuration
FROM dashboard_widget_users
INNER JOIN yw_user ON dashboard_widget_users.dsnr_yw_user = yw_user.intern
INNER JOIN dashboard_widget ON dashboard_widget_users.dsnr_dashboard_widget = dashboard_widget.id
WHERE dashboard_widget_users.dsnr_yw_user =10 AND dashboard_widget.id =1 ";
$result = mysql_query($query, $myConnection);
if ($row = mysql_fetch_assoc($result))
{
$empty_config=$row['configuration'];
if (empty($empty_config)) {
$sql="SELECT dashboard_widget.configuration FROM dashboard_widget WHERE Id =1";
$sql_result = mysql_query($sql, $myConnection);
$results = mysql_fetch_assoc($sql_result);
$config= unserialize($results['configuration']);
}
if (!empty($empty_config)) {
$config = unserialize($row['configuration']);
foreach($config as $val)
{
//Here is my further things.....
}
}
}
You should check if there are any rows found, if so, display the information, if not, display the default info:
<?php
$query = "SELECT dashboard_widget_users.configuration
FROM dashboard_widget_users
INNER JOIN yw_user ON dashboard_widget_users.dsnr_yw_user = yw_user.intern
INNER JOIN dashboard_widget ON dashboard_widget_users.dsnr_dashboard_widget = dashboard_widget.id
WHERE dashboard_widget_users.dsnr_yw_user =10 AND dashboard_widget.id =1 ";
$result = mysql_query($query, $myConnection);
if( mysql_num_rows( $result ) > 0 ) {
// row found, display it
}
else {
// row not found, display default
}
?>
Note: you should look into mysqli_* functions, mysql_* functions are deprecated. Also check this link.
I currently have this query with an array that outputs the variables within using a dynamic input in my form (term), this creates a Dynamic Search with auto complete to fill in all of the details for a product.
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
//$row_array['category_id'] = $row ['category_id'];
$row_array['product_id'] = $row['product_id'];
$row_array['product_names'] = $row['name_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array);
}
mysql_close($conn);
echo json_encode($return_arr);
Unfortunately I also need to get the category_id which is not in the same table, I have tried to modify my query as such, but to no avail:
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' AND `crd_jshopping_products_to_categories` = `product_id` ");
What step am I missing here ? The product_id's match in both tables?
try this query instead and try to understand what I have written in it:
$fetch = mysql_query("
SELECT
p.*,
c.category_id
FROM
crd_jshopping_products as p
INNER JOIN crd_jshopping_products_to_categories as c
ON p.product_id = c.product_id
WHERE
`p.name_en-GB` REGEXP '^$param'
");
This means:
SELECT:
Give me everything from p and the category_id from c.
FROM:
Do this from rows in the tables crd_jshopping_products (referred to as p) and crd_jshopping_products_to_categories (referred to as c), where the rows match on the count of p.product_id is the same as c.product_id.
WHERE:
Only return the rows where p.name_en-GB REGEXP '^$param'.
I would like to know how I could join these 3 queries together as I'm wanting only one JSON output, I thought INNER JOIN would do this. But don't know how to use this. Can someone guide me onto the right path please?
$json = array();
$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT * FROM streamdata WHERE streamitem_id < '$lastID' AND streamitem_target=".$following_string." OR streamitem_creator=".$following_string." ORDER BY streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json['streamdata'] = array();
while ($resultArr = mysqli_fetch_assoc($chant)) {
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['streamdata'] = $json;
}
/***** COMMENTS *****/
$check = "SELECT comment_id, comment_datetime, comment_streamitem, comment_poster, comment_content FROM streamdata_comments WHERE comment_poster=".$following_string." ";
$check1 = mysqli_query($mysqli,$check);
$json['streamdata_comments'] = array();
while ($resultArr = mysqli_fetch_assoc($check1)) {
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['streamdata_comments'] = $json;
}
/***** USERS *****/
$check = "SELECT * FROM users WHERE id=".$following_string."";
$check1 = mysqli_query($mysqli,$check);
$json['users'] = array();
while ($resultArr = mysqli_fetch_assoc($check1)) {
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
$json['users'] = $json;
}
echo json_encode($json);
}
?>
You're fetching unrelated data, so you can't use a join at the SQL level.
But JSON couldn't care less WHAT you feed it, or how. Just build the appropriate PHP-level data structure, e.g.
$data = array();
$data['streamdata'] = array();
... insert data from 'streamdata' query...
$data['streamdata_comments'] = array();
... insert comment data ...
$data['users'] = array();
... insert user data ...
which will give you a 3-way array containing the data from each of your queries. You then pass that entire $data structure to json_encode, and boom - you've got your 3 unrated queries in a single data structure, without every touching an SQL join.
Some previous answers have suggested that you can't join unrelated tables, but these are clearly not unrelated tables. The streamdata and streamdata_comments tables are quite closely related, and the users table maps user ID values in the other tables to names.
At the SQL level, these can be combined easily:
SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_ID = c.comment_streamitem
JOIN users AS u ON u.user_id = c.comment_poster
WHERE c.comment_poster = '$following_string'
AND d.streamitem_id < '$lastID'
AND (d.streamitem_target = '$following_string' OR
d.streamitem_creator = '$following_string');
Whether the result makes sense for wrapping into a JSON string is a different matter, on which I can't pontificate. This would give you one record from the comments information for each comment associated with each stream item.
You are fetching unrelated data. Joining data is only usefull when the data to join has a relation.
You can't join apples, cows and monkeys.