Receiving errors on empty GET variable - php

Im building an application that shows off various types of records for my team as a whole. to start this is the menu (some with $_GET information on them)
The html menu that brings up this page looks like this:
<li>WEB department
<ul>
<li>Mike</li>
<li>Deidre</li>
</ul>
</li>
The webpage that pulls the web data, the important part is this below
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
then further down the page i output the data i want. For example
while($row = mysqli_fetch_array($pullWebTeamDataDoIt)){
//do stuff here - - - **this part never changes**
}
Then this pulls all the records for the web team as a whole. In this fashion i thought "hmm it'd be even more useful if I can display the records for each of the teams members individually.
Obviously, im not going to make an individual page for ALL the members of the company so i thought of re-purposing this page so that if a GET variable equals a persons name, that certain data is shown.
here is the code
$tstname= $_GET['tstname'];
if($tstname == "Mike"){
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
} elseif ($tstname == "Deidre"){
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
} else {
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
}
Now although it pulls the data I want(named get link or normal web link), the problem is that on page load, if the person clicks the regular web page link that doesn't have $_GET information attached. It throws an error because at that point the "$_GET" in:
$tstname= $_GET['tstname'];
doesnt exist. How can i make it so that if the "$_GET" doesnt exist. to just ignore it?
Feels like i should know this....lol anyways,
i tried things like
if(!empty($testname)){ do stuff }
or if($testname) //since this equals to true if not empty...
etc but to no avail. Hope I was clear. any tips/help etc i humbly appreciate.
Thanks in advanced.

use isset
if(isset($_GET['tstname'])) {
// do your stuff
}

Use ternary operator for setting the variable.
$tstname= !empty($_GET['tstname'])? $_GET['tstname']: ' ';
or
$tstname= isset($_GET['tstname'])? $_GET['tstname']: ' ';

$tstname= isset($_GET['tstname'])?$_GET['tstname']:'';

Related

Echo out user information in the same table to their page base on their store information without echoing out the same information to another user

First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.

PHP Echo results where input LIKE $_GET

I'm trying to implement a hashtag system into my website. I have it set so user input that has a hashtag gets converted into a link to hashtag.php?q=%23$1 that echo's "Results for '.$_GET["q"].':"; which works fine, but it doesn't actually display any posts.
For example, I have a post saying "This #website sucks" which is echoed out as
This #website sucks
But the following page only displays
Results for #website:
and the rest is blank. Here's my code for hashtag.php:
echo 'Results for '.$_GET["q"].':';
$connect = mysql_connect("localhost","root","");
mysql_select_db("database",$connect);
$mysql = "SELECT * FROM table WHERE input LIKE '".$_GET['q']."' ";
$myData = mysql_query($mysql, $connect);
while ($record = mysql_fetch_array($myData)){
echo $record['input'];
}
I'm working on using mysqli before I make the site public by the way.
Try putting % percentage signs on either side of the $_GET["p"] in your query. Don't forget to escape the $_GET["q"] as well. That'd be more important than using mysqli ;)
$mysql = "SELECT * FROM table WHERE input LIKE '%".mysql_real_escape_string($_GET['q'])."%' ";

CMS homepage in php

I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.

php enquiry form - part filled from database

Afternoon,
Wondering if anyone can help me. Using tables in a database I've got a form which is pre populated (from the content in the database) depending on the page the user has come in from when an enquiry is made.
Eg. if the user has come in from product A page and clicked on the 'enquiry' button from item c, the enquiry form is already pre populated with the name 'product A' and 'item c'
index.php?id=1&pack=13
This is fine if the user comes in from a product page, however if the user clicks on the enquiry button at a higher level page how do I get just the product name to appear in the form? I would have thought it would have been as simple to just change the code to
index.php?id=1
However that doesn't work - the form is completing blank when doing this.
My php knowledge is very limited therefore any help is hugely appreciated.
The db table I'm wanting to target is say 'Bob', within this table I want to target the id of the individual items which selects the name of the item. This currently works as:
$query = mysql_query("SELECT Bob.Name, Bob_Packages.Name FROM Bob, Bob_Packages WHERE Bob.Id=Bob_Packages.Bob_Id AND Bob.ID = '".$id."' AND Bob_Packages.Id = '".$pack."'");
However I now only want 'Bob.Name' for this particular 'enquiry' link. My brain is frying!!
Many thanks,
Motley
Hi Dalionzo,
Thanks for your reply. However not really sure if it does help me out. In the current enquiry php page I have:
<?php {
$query = mysql_query("SELECT Bobs.Name, Bob_Packages.Name FROM Bobs, Bob_Packages WHERE Bobs.Id=Bob_Packages.Bob_Id AND Bobs.ID = '".$id."' AND Bob_Packages.Id = '".$pack."'");
$result = mysql_fetch_array($query);
echo $result[0];
}
?>
It's basically just the Bobs.Id I want pulling through. I gave what you supplied a try and an error was returned.
Any ideas? Thanks very much.
In your query you're checking for
id=$id AND packages.id=$pack
This means, that if the query is missing one from the URL, it won't find anything at all!
So, what you have to do, is check if one of them is missing, and then create different queries using that
<?php
$query = "SELECT Bob.Name, Bob_Packages.Name FROM Bob, Bob_Packages WHERE Bob.Id=Bob_Packages.Bob_Id";
if($_GET['id'] != '') {
$query .= " AND Bob.ID = '".$id."'";
}
if($_GET['pack'] != '') {
$query .= " AND Bob_Packages.Id = '".$pack."'";
}
mysql_query($query);
?>
Hope this helps you out!
P.S. I haven't tested this...

PHP site URL ID please Help!

Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...

Categories