How to get current page's isset - php

Firstly, I havent been able to find anything useful on the subject, anywhere really.
I'm trying to make something somewhat simular to a forum,
A small explanation,
(And yes, I know its not seo, but I'm only looking for functionality atm.)
Lets say you go to example.com/?1, Then the database entry with the ID of 1 would be displayed on the index page, If you go to example.com/?3 then the DB entry with the ID of 3 would be displayed, etc..
DB Structure
----------------------------------------
| id | label | description | parent_id |
|---------------------------------------
| 1 | General | NULL | 0 |
| 2 | Public | NULL | 1 |
| 3 | Private | NULL | 1 |
----------------------------------------
PHP Code
if ($stmt = $mysqli->prepare("SELECT id, label, description, parent_id FROM categories")) {
$stmt->execute(); // Execute the query.
$stmt->store_result();
$stmt->bind_result($id, $label, $desc, $parent); // Get variables from result.
while ($stmt->fetch()) {
if(isset($id)) {
echo "Hello, This is the $label category";
}
}
}
What i'm missing is a way to get the users current "isset" (.com/?10, .com/?5, ETC) Before the query is run so i can check for that isset in the DB and get the correct values, right now it's outputting all rows in the DB, I would highly appreciate any help with it :)
If you know of a better way of doing something like this(without using a framework), please let me know!

From a terminology standpoint, it sounds like you are interested in understand what parameters are passed in the request's query string.
In your case, you are doing something a little weird in that be having URI format like /?* where * is integer ID value, you would actually be passing a variably named parameter. Since you don't know what the parameter name is, you would have to do something like
$ids_in_query_string = array_keys($_GET);
To store the key names which infer which ID(s) were requested.
What I would suggest is to form your query string like /?id=*, that way you always know which key in $_GET to check against. For example:
$id = null;
if (!empty($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
}
if (!is_null($id)) {
// perform your query for selected ID
} else {
// do something else
}

Related

Cannot get PHP query to return resource to be made into array, I do not have access to connection data

This is for a self test for a college job application so I am not necessarily looking for the exact statement I need, instead I am trying to get a hint as to what direction to look, I DO NOT have access to the actual database to view it:
This problem tasks us with getting some info on a user when given a NetID($user) and clear-text password($password). If the md5-hash of $password matches the Passwrd field for the given user, then display the user's UserID.
I am getting hung up using mysql_query, I feel like that is failing because it doesn't return any value that prints on the screen.
I think I have to us mysql_query not mysqli_query because the latter requires a connection, and in the instruction it says the connection all done for me, so I have no info to put into the connect command.
Here's my code:
<?
function checkPass($user, $password)
{
// You will likely want to use mysql_query($query) AND mysql_fetch_assoc($result);
// YOUR CODE HERE
$md5Password = md5($password);
$query = "SELECT interview_user_info.UserID,
FROM interview_user_info
WHERE interview_user_info.Passwd = '$md5Password'";
$escapedQuery = mysql_real_escape_string($query);
$queryResult = mysql_query($escapedQuery);
$rowArray = mysql_fetch_array($queryResult, 'MYSQL_NUM');
$UserID = $rowArray[0];
return $UserID;
}
?>
Here is the text and table info from the page:
int checkPass ( string $user , string $password )
Write a PHP function "checkPass" that takes two arguments: $user and $password and returns the UserID if the password matches the MD5 encoding of the appropriate password in the interview_user_info table below and -1 otherwise.
The $user variable contains the NetID of the individual; the $password variable contains a clear-text version of the password as submitted.
+---------------------------------------------------------------------------------+
| interview_user_info |
+-----------+-------------+-----------+--------+----------------------------------+
| UserID | LastName | FirstName | NetID | Passwd |
+-----------+-------------+-----------+--------+----------------------------------+
| 469562029 | Gonzalez | Shauntee | sgonz | 530b4a0ae65148d112537bc0eafba9c9 |
| 702930431 | Bates | Austin | abates | 9cdfb439c7876e703e307864c9167a15 |
+-----------+-------------+-----------+--------+----------------------------------+
The connection and database selection are taken care of. Write the query to pull data from the table "interview_user_info", and return the result. The connection will be closed for you.
Hint: You will likely need to make use of the following functions and possibly others: md5, mysql_query, mysql_fetch_assoc

Passing Primary key "id" all value in URL Parameter : PHP - MYSQLI

I want to pass my primary key all id value in single url parameter :
PRODUCT TABLE :
id -- int 11 , primary key
name -- varchar
desp -- varecha
table data :
id | name | desp
------------------------
1 | A | f
2 | B | fg
3 | C | ghb
4 | g | bn
below code :
$sql = "SELECT id from product";
$result = mysqli_query($db,$sql);
while ($myrow = mysqli_fetch_array($result)){
$id = $myrow['id'];
// echo $id : 1234
}
hence i am getting id value but i need to pass this "id" value in single URL PARAMETER:
<a href="test.php?test=".$_GET['tes']."&pid=".$id." " >url parameter</a>
note : i cant keep this anchor link in my while loop , as i want this a single link that will be shown in another table
hence my link would be something like :
test.php?test=as&pid=1234
but i am unable to get pid=1234
hence please let me know how i can get the same
Editing answer, as I got your idea wrong.
All you have to do is:
while ($myrow = mysqli_fetch_array($result)){
//.= means that it will connect all values, not override them
$id .= $myrow['id'];
// echo $id : 1234
}
THen echo $id from anywhere.
declare an array outside the while loop : $arr = array();
then write this statement inside your while loop : arr[] = $myrow['id']; this way the array will contain all the IDs and it will increment automatically (you don't have to specify the array index each time). Then you can use that array to get the IDs any time you want. Please if that is not what you want, tell me and explain to me more (because I answered your question based on what I understood so please explain more to me about what you need if it is not the answer). Thanks :)

Issue in displaying data that should just be visible for a particular ID not to all

I am trying to display records of a particular job that has already been done by someone else before a new provider sees it. If the status is open, there should not be any information to be displayed as supposedly, no one has made any report about it. If the status is awarded, then necessary data should be displayed. Right now, the information to be shown are viewable. The problem the data is displayed in every job post even it is not the report for such a job.
Example,
Job ID | Title | Description | Subject | Job Status
2 | Math Tutor | I need Math tutor! I need Math tuto... | Mathematics | Open
1 | English Tutor | Edited... | French | Awarded
If I click "Open", I should not be able to see any record because it is still not done. If I click "Awarded", I should see details about the job. Right now, the data is showing properly for JOB ID 1 which was already awarded. However, the same data is shown as well in JOB ID 2.
How do I properly display the data in its proper place? I've been trying everything to do it. I included the JOB ID to be displayed to see if there's something wrong with it. But there's none, it shows JOB ID 1 in both jobs 1 and 2. How do I display it just in job 1 where it belongs?
Here's my code in controller:
public function view_tutors_tutorials()
{
$this->validateRole('provider');
$this->load->model('tutorial_model');
$this->load->model('auth_model');
$data['subject_list'] = $this->array_to_select( $this->tutorial_model->get_all_subjects(), 'id','name');
$my_preference = $this->tutorial_model->get_tutors_tutorials(isset($_GET['subject_id'])?$_GET['subject_id']:'0', isset($_GET['sort_by'])?$_GET['sort_by']:'');
$data['my_preference'] = $my_preference;
$this->load->view('provider/view_tutors_tutorials', $data);
}
and this in my model:
public function get_tutors_tutorials($subject_id = NULL, $sort_by = NULL)
{
//responsible for displaying job contracts for provider user.
$this->db->select('tutorial.status as status, tutorial.client_id as client_id, tutorial.id as tutorial_id, subject.name as name, tutorial.title as title, tutorial.description as description, tutorial.start_date as start_date, tutorial.update_date_time as update_date_time,tutorial_proposal.provider_id as provider_id,provider.first_name as first_name,provider.last_name as last_name,tutorial.contract_status as contract_status,tutorial.provider_feedback as provider_feedback,tutorial.client_notetoself as client_notetoself,tutorial.client_feedback as client_feedback,tutorial.provider_notetoself as provider_notetoself,tutorial.material_used,tutorial.recommendation')->from('tutorial');
$this->db->join('subject', 'subject.id = tutorial.subject_id');
$this->db->join('tutorial_proposal', 'tutorial_proposal.provider_id = tutorial.provider_id');
$this->db->join('provider', 'provider.id = tutorial_proposal.provider_id');
$this->db->where('tutorial.status', 'Awarded');
if ( ! empty($subject_id) )
{
$this->db->where('subject_id', $subject_id);
}
//if there's no sort selection made, the jobs will be sorted from newest to oldest
if ( empty($sort_by))
{
$sort_by = "update_date_time desc";
}
$this->db->order_by($sort_by);
$query = $this->db->get();
return $query->result_array();
}
I look forward to getting any help.
You need to remove where condition for status in you model's query :
$this->db->where('tutorial.status', 'Awarded'); // this should be removed
Also make sure, your subject_id passed properly.

MySQL insert multiple rows into a table if they don't already exist

If I have a table like this:
+-------------+-------------+
| Field | Type |
+-------------+-------------+
| document | varchar(35) |
| section | int(11) |
| selection | int(11) |
| status | varchar(35) |
+-------------+-------------+
And I have an array in PHP. Let's call it $choices[]. The column selection coresponds to an array index for the choices array. If I add an element or elements to the $choices array then I need to update the database. I'd be operating in a loop where $document and $section are also set. I don't want to assume that there are no missing rows in the middle of my numbering. What's the most efficient way to check for (document,section,selection) for each element in $choices, create any that does not exist, and set its status to "new"?
Do I have to do this as a loop, or is there a way to do this in one query?
This is completely untested, but this is basically how I'd do it if I didn't ask for help. I guessed someone might have a MUCH better solution than me.
foreach($documents as $document)
{
foreach($sections as $section)
{
$choices=$master_array[$document][$section];
$ch_count=count($choices);
$counter=0;
while($counter < $ch_count-1)
{
$query="SELECT status FROM mytable WHERE document='$document' AND section='$section' AND selection='$counter'";
$result = mysql_query($query);
if(mysql_num_rows($result)==0)
{
$query="INSERT INTO mytable VALUES('$document','$section','$counter','new')";
$result = mysql_query($query);
}
$counter++;
}
}
}
If everything is going to be updated with "new", then this can be achieved somewhat easily.
Examine the following code:
<?
$setStr = "";
foreach($choices as $column)
{
$setStr .= $column . "=" . "'new', ";
}
$sqlCommand = "UPDATE table SET ".substr($setStr,'',-2)." WHERE pick_a_row_here;";
echo $sqlCommand;
?>
For the ones that do not exist, try configuring it so their values are default to false when unspecified. Of course an INSERT statement can easily be adapted from my above UPDATE statement.
Let me know what you think. If you have questions or comments, I'll do my best to answer them.
I ended up using a loop to contatenate together a large query string that looked something like this, except much larger:
INSERT IGNORE INTO mytable VALUES
('doc1','1','0','New'),
('doc1','1','1','New'),
('doc1','1','2','New'),
('doc1','1','3','New'),
('doc1','2','0','New'),
('doc1','2','1','New'),
('doc1','2','2','New'),
('doc1','2','3','New'),
('doc1','3','0','New'),
('doc1','3','1','New'),
('doc1','3','2','New')
And it works. Whether or not its the best, I don't know but at least I'm not sending hundreds of queries to the DB.

PHP Advanced Search

I am currently making a website where I require a very advanced search engine. I want the users to be able to say Person # company or Product # Category. How would I detect the # sign or any special characters, filter them out and make individual variables based on the returned string. So $a = Person and $b = company.
You can use explode() to split a string:
$items = explode('#', 'Person # Company', 2);
if(count($items) === 2) {
// Person # Company
$person = trim($items[0]);
$company = trim($items[1]);
// Do your searching here...
} else {
// Search normally, not Person # Company.
}
Send it across as a get request formatted as a=Person&b=company etc. The other way is exactly what you said, loop through the string and examine the chars one by one. When you encounter an # sign you know that the letters before it (not including spaces) are the value of a and everything after the # (not including spaces) is the value of b.
Sorry I tried to be as clear as I could.
This is very simple to achieve;
function searchForPersonAtCompany($searchQuery) {
global $db;
$queryComponents = explode('#', $searchQuery, 2);
if (count($queryComponents) != 2) {
// '#' was not specified in the search query, return an empty array.
return array();
}
$person = $queryComponents[0];
$company = $queryComponents[1];
$sql = 'SELECT p.id AS personId, c.id AS companyId FROM people p JOIN companies c ON p.company = c.id WHERE p.name LIKE :person AND c.name LIKE :company';
$stmt = $db->prepare($sql);
$stmt->bindValue(':person', $person);
$stmt->bindValue(':company', $company);
$stmt->execute();
return $stmt->fetchAll();
}
You didn't specify your database schema, so I had to guess that you have a people table and a companies table, with people related to the companys table with the company field.
Table: People
id | name | company
--------------------------------------------
1 | Alice | 1
2 | Bob | 1
3 | Charles | 2
Table: Companies
id | name
--------------------------------------------
1 | Company A
2 | Company B
You will have to adapt the code for your purposes, but using my testing data, the following should work;
searchForPersonAtCompany('Alice#Company A');
searchForPersonAtCompany('Charles#Company B');
Notes:
This is a very simple implementation of your search, you might be better looking into a database based search engine which can handle more complicated queries for the future.
I have used PDO as the connection to my database (bindValue, exec, etc), you might be using something different. :person and :company are just variables in the SQL.

Categories