I'm developping a website where there are ajax request to get data from a mySQL database.
To simplify the problem, let's say I have the following database structure :
Table OBJECT
ID_OBJECT (int)
NAME_OBJECT (varchar)
Table IMAGE
ID_OBJECT (int) -> foreign key from OBJECT
URL (varchar)
So every object can have between 0 and n images attached to it.
I'm stuck at writing the php script that request the data.
To simplify again, let's say I want to get all objects with all the images they have (but in the future I'll want to get any specific object with all its picture too)
I have written this PHP script :
$sql = "select
ID_OBJECT,
NAME_OBJECT,
URL
from
OBJECT,
IMAGE
where
OBJECT.ID_OBJECT = IMAGE.ID_OBJECT";
$statement=$db->prepare($sql);
$statement->execute();
$result=$statement->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
The problem I have is as soon as I add "URL", "IMAGE" and the where statement in the sql query, it doen"t echo anything.(I have several objects and images in my databases with the propers ids). I don't understand where I'm making a mistake here.
ID_OBJECT is in both tables, so MySQl doesn't know which one to show. Try specifying like this:
select
OBJECT.ID_OBJECT,
OBJECT.NAME_OBJECT,
IMAGE.URL
from
OBJECT,
IMAGE
where
OBJECT.ID_OBJECT = IMAGE.ID_OBJECT
Obviously you have an error in your query. You should set what ID_OBJECT field you want - from first or second table.
Rewrite your query like:
select
o.ID_OBJECT,
o,NAME_OBJECT,
i.URL
from
OBJECT o,
IMAGE i
where
o.ID_OBJECT = i.ID_OBJECT
Related
As part of a search routine for a specific crop, I'm making two calls to the same database table, merging the results and sending them down the line. The first call looks for data relating to the searched-for crop (e.g. "beans"). The second call looks for data relating to the crop group of that crop (e.g. legumes).
Data returned from the first call will be more relevant/focused than that from the second call. I want to add an identifier to the respective data sets that reflects this so that I can subsequently sort/present the data on the basis of relevance in my Vue component.
The following code extracts the crop-specific information from the database; how can I add/insert/append a new variable (e.g. "relevance" = 1) to each row in $factsheets before I "array_merge" it with the data returned from the crop-group sql call?
(For sake of simplicitly, I've not included the code that determines the crops.id value from the name of the crop entered by the user.)
public function getFactsheets($cropId){
$factsheets = Factsheet::whereIn('crop_id',$cropId)
->join("crop_factsheet as cf","factsheets.id","=","cf.factsheet_id")
->join("crops as crops","crops.id","=","cf.crop_id")
->select('crops.name','title', 'factsheets.id', 'shortdesc', 'shortimg', 'factsheets.slug')
->orderBy('crops.name')
->get()->toArray();
return $factsheets;
}
Thanks, Tom.
If you give & to value so whatever changes will happen to value will directly saved on its address.
foreach($factsheets as $key => &$factsheet){
$factsheet['relevance'] = 1;
}
Working demo.
Here is concise explanation of references in official doc.
you can simply do a foreach
foreach($factsheets as $key => $factsheet){
$factsheet['relevance'] = 1;
}
I've got a page with the following url: website.com/foo/bar
Where foo is the page's php file and bar is the corresponding id to be used to pull in the data from the database.
I'm not using any sort of framework trickery. Just an htaccess to remove the .php and extensions and to process the page foo.php with the id as its not in a sub-folder.
Anyways, bar is just a number (like I said corresponds with database row id). For SEO and general readability in a users history I want to go to the more popular website.com/foo/this-is-the-name format (what is this format called??).
Currently my code is:
require('neou_cms/framework/framework.php');
$id = filter(basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
// no id
if (empty($id)) {
header('Location: ../portfolio');
}
$projects = Nemesis::select("*", "projects", "published = '1' AND id = {$id}");
$row_projects = $projects->fetch_assoc();
$totalRows_projects = $projects->num_rows;
// no results, bad id
if ($totalRows_projects <= 0) {
header('Location: ../portfolio');
}
If figure I would do the following (1) make it so that the pages linking to foo instead go to the page title e.g. /this-is-the-name (2) in foo i'd make it so that $id removes the dashes from the name and searches the database for the row using a select statement and the title.
However I feel like this is slow... Is there a better way to do it that wouldn't require me changing the current flow?
Your approach is fine. The this-is-the-name part of your url (website.com/foo/this-is-the-name) is commonly called a "slug". If you'll be querying a database table on the slug, just make sure the slug column has an index and the query should perform reasonably well.
I would also like to point out that you have a SQL injection vulnerability in the code you've posted. Consider binding $id as a parameter in a parameterized query instead of dynamically including it in a where clause.
I have an online MySQL where a table has a column containing an https URL which is stored as varchar(255). For example, here's a screenshot from phpMyAdmin:
The strange thing which is actually happens, is that when I get the data from MySQL through PHP and I encode them into JSON (so that to be delivered to an iOS app) then the caption is always null. Here's my code:
public function fieldInfoByFishID($fish_id){
$sql = mysqli_query($this->config->dbConn,"SELECT * FROM ".$this->config->table_fields." WHERE id_fish='".$fish_id."'");
$v = mysqli_fetch_array($sql,MYSQLI_ASSOC);
$tmp = array(
'id'=>$v['id'],
'id_fish'=>$v['id_fish'],
'description_info'=>utf8_encode($v['description_info']),
'recognition_info'=>utf8_encode($v['recognition_info']),
'place_info'=>utf8_encode($v['place_info']),
'fishing_method'=>$v['fishing_method'],
'buy_period'=>$v['buy_period'],
'caption'=>$v['caption'],
'life_method'=>utf8_encode($v['life_method']),
'exploitation_status'=>$v['exploitation_status']
);
return $tmp;
}
The code looks correct to me but I don't know why that column is not fetched. Is there a particular attention I have to pay in order to get the url correctly? I thought it was just a simple string.
Here's an example:
Obviously, if I tr to exec the sql query in phpMyAdmin console, it all works fine.
Thank you all.
I have a mySQL database table setup called site.
Rather than qet the column headings to produce a PHP object of values I want to produce data from the rows.
TABLE: site
:::field:::::value:::::
url www.example.com
name example site
etc Example Etcetera
So I want to be able to get this information from the server by calling the column name I want and the row I am after. I want to do this for all fields in site as I don't want to do multiple calls for the various different rows in site; I'd rather store all the information from the beginning in the object:
eg. <? echo $site['url']; ?>
I created this put it appears to be causing an error:.
$sql = "SELECT * FROM `site`";
$site[];
foreach($sodh->query($sql) as $sitefield){
$site[$sitefield['field']] = $sitefield['value'];
}
Obviously I've missed something. ¿Any idea as to what?
$site[];
should be
$site = array();
I'm trying to use the Joomla framework to make a create in the main content table.[http://docs.joomla.org/How_to_use_the_JTable_class] This works fine except that some data comes from posted variables and some from logic that happens when a file is uploaded moments before (store the random image name of a jpg)
$data=&JRequest::get('post');
this takes a ref to the posted values and I want to add to this Array or Object my field. The code I have makes the new record but the column images, doesnt get my string inserted.
I am trying to do something like$data=&JRequest::get('post');
$newdata=(array)$data;
array_push($newdata,"images"=>"Dog");
i make newdata as data is a ref to the posted variables and i suspect wont there fore allow me to add values to $data.
I'm a flash guy normally not a php and my knowledge is letting me down here.
Thanks for any help
Right, first thing:
$data=&JRequest::get('post');
$data is an array, you do not have to cast it. To add another element to the array as described in the comments do this:
$data['images'] = 'cats';
If you are using normal SQL to do the insert then you would do something like this to get the last inserted id e.g. the id of the row you just inserted:
$db = $this->getDBO();
$query = 'Some sql';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseWarning(100, 'Insert failed - '.$db->getErrorMsg());
}
$id = $db->insertid();
If you are developing in Joomla I suggest you use the db functions provided to you rather than mysql_insert_id();
[EDIT]
If you want to use store then you can get the last inserted id like so:
$row->bind($data);
$row->check();
$row->store();
$lastId = $row->id;