Get column value from a foreign key reference in PHP - php

My output is only id column, reference to "combustibili" table. How to get value reference from combustibili?
$combustibili = "SELECT * FROM tabelint";
$rezcom = $conectare->query($combustibili);
$p = new GNUPlot();
while($row = $rezcom->fetch_assoc()) {
if($row["ID"] == 1){
$data = new PGData($row["ID_BENZINA_STANDARD"]);
$data2 = new PGData($row["ID_MOTORINA_STANDARD"]);
$data3 = new PGData($row["ID_BENZINA_SUPERIOARA"]);
$data4 = new PGData($row["ID_MOTORINA_SUPERIOARA"]);
}
}

From information provided assume COMBUSTIBILItable structure should be something like
COMBUSTIBILI(id pk and fk_in_tabelint number, name varchar, price float)
TABELINT(id pk number, ID_BENZINA_STANDARD fk->COMBUSTIBILI number ... etc)
so
SELECT * FROM tabelint where id=1 will retun something like
(id #1, ID_BENZINA_STANDARD #2 ... etc)
and just need to query COMBUSTIBILI with fks
$combustibili = "SELECT * FROM tabelint";
$rezcom = $conectare->query($combustibili);
$p = new GNUPlot();
//assume also record for id=1 exists
while($row = $rezcom->fetch_assoc()) {
if($row["ID"] == 1){
$data = new PGData($row["ID_BENZINA_STANDARD"]);
$data2 = new PGData($row["ID_MOTORINA_STANDARD"]);
$data3 = new PGData($row["ID_BENZINA_SUPERIOARA"]);
$data4 = new PGData($row["ID_MOTORINA_SUPERIOARA"]);
}
}
//add for each id_s
//BENZINA_STANDARD :: should be 1 row if db is consistent
//not sure how PGData class is defined and how to retrive only id : maybe $pgd->id ...
//$data = $row["ID_BENZINA_STANDARD"] : this is what is needed
$sql = "SELECT * FROM COMBUSTIBILI where id=".$data;
$sqlout = $conectare->query($sql);
//just parse and retrive what ever wanted
while($row = $sqlout->fetch_assoc()) { ... etc ... }
//same with data2_3_4

Related

how to update column without using auto_increment value with 001 to so on

This is my table with name and unique numberenter image description here
This is my PHP code
$id = explode(",", $params["txtID"]);
for ($i = 0; $i <count($id); $i++) {
$sql = "SELECT 'auto_increment' as LastID FROM
INFORMATION_SCHEMA.TABLES WHERE table_name = 'esi_master' ";
$result = $this->con->query($sql);
if (intval($result->rowCount($result)) > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$lclId = intval($row["LastID"]) - 1 + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
} else {
$lclId = intval($row["LastID"]) + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
$sql = $this->con->prepare("UPDATE esi_master SET esi_status = 1,
esi_dcno = '$lclDcno[$i]' Where esi_id = '$id[$i]'");
echo $result = $sql->execute();
}
Here First I insert Names to the table using Insert Statements and next for some operation I update the Unique number unique number should start updating from the empty row, update done with unique id, The txtID contains ID`s like 1, 2, 3, 4 so on as I select table row in front end, in that basis that updates.Thanks in Advance.
You need another field to save, with type varchar(10).
data will not be able to save into integer(auto_increment)

mySQL seperate data stored in table

currently I have two pieces of data being stored in a sql db and then pulled into my website. What I want though is the two pieces of data being stored to be separated instead of totaled together.
So i setup my DB like so:
DROP TABLE IF EXISTS totals;
CREATE TABLE totals (
id int(11) NOT NULL AUTO_INCREMENT,
total float NOT NULL,
PRIMARY KEY (id)
) ;
INSERT INTO totals VALUES (1, 0);
And the PHP I'm using:
$api = array();
$api[] = 'http://api.jo.je/justgiving/data/myuserpage';
$api[] = 'http://api.jo.je/justgiving/data/myuserpage2';
$total = 0;
foreach($api as $data) {
$open = file_get_contents($data);
$feed = json_decode($open);
if(is_object($feed)) {
$total = $total + $feed->donations_total;
}
}
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); // new data
$id = 1;
// query
$sql = "SELECT total
from totals
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($id));
$data = $q->fetch();
$total = $data['total'];
Being a noobie at this, I just need some help storing two seperate pieces of data instead of one.
I think you simply want two separate columns in the table:
CREATE TABLE totals (
id int(11) NOT NULL AUTO_INCREMENT,
total1 float NOT NULL,
total2 float NOT NULL,
PRIMARY KEY (id)
) ;
$api = array(
'total1' => 'http://api.jo.je/justgiving/data/myuserpage',
'total2' => 'http://api.jo.je/justgiving/data/myuserpage2',
);
// The saving part is missing from your code, but it should be something like
$sql = "UPDATE totals SET {$source}=? WHERE id=?";$q = $conn->prepare($sql);
$query = $conn->prepare($sql);
// Note: the above assumes that the "id" already exists. Otherwise
// you need an "UPSERT" (UPdate or inSERT) that will insert a new value or update
// it if it already exists. Find more # this answer:
// https://stackoverflow.com/questions/15383852/sql-if-exists-update-else-insert-into
/*
* Instead of adding up the two API calls' results, we store them separately
*
* Of course the value of "id" here must be the same as in the second page, or
* what you will retrieve will NOT be what you have stored!
*/
foreach($api as $column => $source) {
$data = file_get_contents($source);
$feed = json_decode($data);
if (is_object($feed)) {
$value = $feed->donations_total;
$query->execute(array($value, $id));
}
}
Now in the second page
// query
$sql = "SELECT total1, total2 from totals WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($id));
$data = $q->fetch();
$total1 = $data['total1'];
$total2 = $data['total2'];
(This is the link to the answer referred above).

SQL / PHP How to pull data from a table and place it in variable

Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

mysql query returns the value in the first column for all the other columns

Hi I made a query to a table below and when I tried to get the value in each column , it returns the same value from the first column for all the other columns.
To elaborate
In my database table I have the following:
owner_id = 21
pet_id = 1
name = fluffy
color = green
type = dog
sub_type = boxer
location = LA
however whenever I try to access one column, say the name column, it returns 21 which is the
value in the owner_id column corresponding to that pet_id. I am not sure why this is
happening.
$query = sprintf("SELECT * FROM `petAttributes` where pet_id ='%d'",$p_id);
$result = performQuery($query);
$owner_id = stripslashes(mysql_result($result,"owner_id"));
$pet_id = stripslashes(mysql_result($result,"pet_id"));
$name = stripslashes(mysql_result($result,"name"));
$color = stripslashes(mysql_result($result,"color"));
$type = stripslashes(mysql_result($result,"type"));
$sub_type = stripslashes(mysql_result($result,"sub_type"));
$loc = stripslashes(mysql_result($result,"location"));
Information on my environment
PHP Version 5.2.14
MYSQL version 5.0.67
I believe that if you use mysql_result you also have to specify the row index number (row 0 in your case?), before you specify the column.
$name = stripslashes(mysql_result($result, 0, "name"));
refering to http://php.net/manual/en/function.mysql-result.php mysql_result has it's parameters like this: mysql_result($result,$rownumber,$fieldname or $fieldnumber)
this should workd:
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$owner_id = stripslashes(mysql_result($result,0,"owner_id"));
$pet_id = stripslashes(mysql_result($result,0,"pet_id"));
$name = stripslashes(mysql_result($result,0,"name"));
$color = stripslashes(mysql_result($result,0,"color"));
$type = stripslashes(mysql_result($result,0,"type"));
$sub_type = stripslashes(mysql_result($result,0,"sub_type"));
$loc = stripslashes(mysql_result($result,0,"location"));
BTW mysql_result is getting very inefficient if you take more than one row.
Then you should use mysql_fetch_row, mysql_fetch_array or mysql_fetch_assoc
Also you can;
for only first row
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$row = mysql_fetch_array($result);
extract($row);
or all returned rows;
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
while($row = mysql_fetch_array($result))
{
foreach ($row as $value) echo $value."<br>";
}

Categories