Ok So i have an PHP page and i have a database.
In my database i have a table with a Field one of the fields is called accounttype it is enum('n', 'm', 's')
I am trying to display on my PHP page if the user is N it should say Normal User if the user is E Expert user or S Super user...
How do i go about doing this?
Top of PHP Page
<?php
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM members WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
$phone = $row["phone"];
$country = $row["country"];
$state = $row["state"];
$city = $row["city"];
$accounttype = $row["accounttype"];
$bio = $row["bio"];
}
?>
Where i am trying to display on the page This is the code. Right now it just puts a blank space.
<span class="admin">Edward</span>
<span class="date">March 19, 2048</span>
<span class="tag"><?php echo "$accounttype"; ?></span>
<span class="comment">166 comments</span>
picture
http://i.stack.imgur.com/KXu9A.png
first make a connection, than dont make a while, make a if like this
if($row = mysql_fetch_array($sql)){
$phone = $row["phone"];
$country = $row["country"];
$state = $row["state"];
$city = $row["city"];
$accounttype = $row["accounttype"];
$bio = $row["bio"];
}
and than
$speaking_type = null;
switch($accounttype) {
case 'n':
$speaking_type = 'Normal User';
break;
case 'm':
$speaking_type = 'Expert User';
break;
case 's':
$speaking_type = 'Super User';
break;
default:
$speagink_type = 'none';
//throw new Exception('unsupported account type '.$accounttype);
}
echo $speaking_type;
I think the problem is your scope. Your variables are defined within the while-loop, and so they are unknown further in the document. Try instantiating them on top (before the while-loop) like this:
$phone = null;
$country = null;
$state = null;
$city = null;
$accounttype = null;
$bio = null;
Than the variables will be known outside the while and the values will be remembered when you print them.
I thought u didn't connect to the database first .use following code to the connect with your credentials.That's why you are seeing a blank space
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
Related
So i've got a table full of data. I have a page where i list all the contents of that able out through a while loop. Then the user can click a button on a record and it will generate an address label using the data it has and the generated label is done in a PDF. So that all works fine and dandy. However i was wondering is it possible to replace that button with an HTML Checkbox for each record to something like this
<input type="checkbox" name="<?php echo $recordTitle; ?>" />
<input type="hidden" name="<?php echo $recordID"; ?>" />
So this would allow people to select multiple records and then click one button and it would take all of those records and generate as many labels as it needed too. If this is possible, how would i process all of that, because i'd need to somehow loop through all the records the user has selected.
<?php
$eventSearch = $_POST['eventSearch'];
//Include Database connection
include '../includes/dbConnect.php';
foreach ($arr as &$value) {
$id = $value;
//Query Database for all customer info
$sql = "SELECT * FROM customerInterest WHERE `id` = '$value'";
$result = mysqli_query($dbLink, $sql);
$row = mysqli_fetch_assoc($result);
//require the document that creates the PDF
require('PDF_Label.php');
//Create a new PDF
$pdf = new PDF_Label('L7163');
$pdf->AddPage();
//assign the customer information to a variable
$sal = $row["salutation"];
$fn = $row["firstName"];
$ln = $row["lastName"];
$add1 = $row["contactAddress1"];
$add2 = $row["contactAddress2"];
$city = $row["contactAddressCity"];
$state = $row["contactAddressState"];
$post = $row["contactAddressPostcode"];
$country = $row["contactAddressCountry"];
if ($sal == "N/A") {
$sal = "";
}
if ($fn == "N/A") {
$fn = "";
}
if ($ln == "N/A") {
$ln = "";
}
if ($add1 == "N/A") {
$add1 = "";
}
if ($add2 == "N/A") {
$add2 = "";
}
if ($city == "N/A") {
$city = "";
}
if ($state == "N/A") {
$state = "";
}
if ($post == "N/A") {
$post = "";
}
if ($country == "N/A") {
$country = " ";
}
$add1 = $add1." ".$add2;
$post = str_replace(' ', '', $post);
$post = strtoupper($post);
$post = substr_replace($post, " ", 4, 0);
// Standard format
//create new page
// Print labels
$text = sprintf("%s\n%s\n%s\n%s %s",$sal." ".$fn." ".$ln, $add1, $city, $state, $post,$country);
$pdf->Add_Label($text);
}
//Output all the info
$pdf->Output();
?>
So the above contains the code i have now tried. I have posted the data to the PDf generating page (that is where all the code is from) and i keep getting the error (see below) and i cannot figure out why :/
Fatal error: Uncaught Error: Call to a member function Output() on null in /homepages/38/d735513801/htdocs/future/pdfGen/labelEX.php:80 Stack trace: #0 {main} thrown in /homepages/38/d735513801/htdocs/future/pdfGen/labelEX.php on line 80
So my whole question in in the Title,but lets make it easier for you guys to understand.Now when there is an empty field in database php returns "0"There is an example:
I need when there is an empty spot this to be displayed,and by this i mean the "-" or "~" sign.
So is there way to make that automatic with PHP,when field is empty instead of "0" any symbol to be displayed,and if there is pleasee tell me <3
There is my Code:
<!--------------------------------------------------------------------------
PHP CODE
--------------------------------------------------------------------------->
<?php
$page_id= $_GET['id'];
$hostname = "localhost";
$username = "shreddin";
$password = "!utf55jyst";
$databaseName = "shreddin_nation";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$connect->set_charset("utf8");
$query = "SELECT * FROM food_data_bg where id = '" . $page_id . "'";
$result = mysqli_query($connect, $query);
?>
<?php while($row1 = mysqli_fetch_assoc($result)):; ?>
<?php
if (mysqli_num_rows($result) == 0){
echo "daaaaa";
}
$title= $row1['title'];
$fimage = $row1['fimage'];
$state = $row1['state'];
$carbs = $row1['carbohydrates'];
$proteins = $row1['proteins'];
$fats = $row1['fats'];
$caloriesTotal = $row1['calories total'];
$carbsCalories = $row1['carbs cal'];
$protCalories = $row1['prot cal'];
//and so on ...
//and after the all variables i am just displaying results in html elements like so
?>
<!--------------------------------------------------------------------------
HTML EXAMPLE
--------------------------------------------------------------------------->
<div class="food-macros"><b>Общи Калории</b><span><?php echo $caloriesTotal; ?></span></div>
<div class="food-macros"><b>Протеин</b><span><?php echo $proteins ?></span></div>
<div class="food-macros"><b>Въглехидрат</b><span><?php echo $carbs; ?></span></div>
<div class="food-macros"><b>Мазнини</b><span><?php echo $fats; ?></span></div>
Sorry if there is a mistake or something missing,i will fix and link everything you guys need to help me after get back from university,THANKS <3
for each item in your database you want to check if is ZERO (0):
$carbs = ($row1['carbohydrates'] === 0) ? "-" : $row1['carbohydrates'];
/// === means strictly same value
and so on...
EDIT:
function zeroField($field, $replace = "-")
{
return ($field === 0) ? $replace : $field;
}
usage:
$carbs = zeroField($row1['carbohydrates']); //output: "-" or field value
//or change sign
$carbs = zeroField($row1['carbohydrates'],"~"); //output: "~" or field value
I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.
I'm working on a filter in which results are filtered right away, I'm wondering if that may be the cause of the problem so I thought I would ask and see if anyone could give me a pointer on how to proceed.
<script>
var services = [
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$url = $row["$url"];
$title = $row["$title"];
$amount = $row["$amount"];
$id = $row["$id"];
$status = $row["$status"];
$nonprofit = $row["$nonprofit"];
echo '{"permalink": "';
echo "{$url}";
echo '",';
echo '"title": "';
echo "{$title}";
echo '",';
echo '"amount":';
echo "{$amount}";
echo ',';
echo '"id": "';
echo "{$id}";
echo '",';
echo '"status": "';
echo "{$status}";
echo '",';
echo '"address": "';
echo "{$address}";
echo '",';
echo '},';
}
}
?>
]
//]]>
</script>
<script id="template" type="text/html">
<a title="{{title}}" href="{{permalink}}">
<div class="fs_box hide-for-small-down">
<div class="fs_left">
<span class="fs_head">{{title}}</span>
<span class="fs_id"><img src="images/{{id}}.jpg" width="75%" height="75%" onError="this.onerror=null;this.src='images/logo.png';"></span>
<span class="fs_status">{{status}}</span>
<span class="fs_disc">{{address}}</span>
</div>
<div class="fs_price">${{amount}}+</div>
<div class="clear"></div>
</div>
</a>
</script>
I'm expecting it to produce a bunch of results that then are filtered criteria which are elsewhere in the page.
When I try it currently just as a php code it outputs fine. However, when I try it in the php file that this should go in it produces nothing. Or does it dislike being in a script?
Thanks for any help!
You can use json_decode and json_encode to turn an array to json and json back to an array.
Also someone will probably mention that you should not be using the mysql_* functions in PHP as they are depreciated.
Something like this:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
$results = array()
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
$json = json_encode($results);
}
?>
]
<script>
var services = <?php echo $json; ?>;
</script>
This would give you a json object to use to render in your script.
What extension is the file you are saving?
If it's not .php or an extension set to render php, then you'll just have the code show up as test.
You might want to pull out the "die" statement after the db connect. This looks like you are running php in a .js file so you probably want the entire file to write out rather than stop because you couldn't connect to the database (or at least give 0 results, maybe a warning)
I'm still learning more interesting details about PHP. Example: Moving from MySQL to MySQLi. What I am currently doing is trying enter something like this: http://music.daum.net/artist/main?artist_id=2289
From what I learned from pagination by dicing the url:
main?
artist_id=
2289
How can I be able to make a page like that? I have 2 sections available and will make the others when figuring this out.
artist information (available as testhub-artist.php)
album (available as testhub-artistalbum.php)
music video
photo section
I want to make it easier when making pages instead of making separate folders for each person.
My url would be: "../artist/detail?artist_id=#"
This is at the top of the artist page.
<?php
//Connect to ...
include "testhub-artist.php";
include "testhub-artistalbum.php";
?>
testhub-artist.php
<?php
//Connect to database
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT * FROM individuals WHERE soloID = 1";
// Create results
$result = mysqli_query($link, $sql);
// Checking if query is successful
if($result){
// Print out the contents of each row into a table
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
// If else states on each variable
if ($profilepic = $row['profilepic']){
$profilepic = $row['profilepic'];
}else{
$profilepic = "DamjuNoImage";
}
if ($engname = $row['engname']){
$engname = $row['engname'];
}else{
$engname = "Unknown";
}
if ($korname = $row['korname']){
$korname = $row['korname'];
}else{
$korname = "Unknown";
}
if ($engbn = $row['engbn']){
$engbn = $row['engbn'];
}else{
$engbn = "Unknown";
}
if ($korbn = $row['korbn']){
$korbn = $row['korbn'];
}else{
$korbn = "Unknown";
}
if ($dateofbirth = $row['dateofbirth']){
$dateofbirth = $row['dateofbirth'];
}else{
$dateofbirth = "Unknown";
}
if ($occupation = $row['occupation']){
$occupation = $row['occupation'];
}else{
$occupation = "Unknown";
}
if ($debut = $row['debut']){
$debut = $row['debut'];
}else{
$debut = "Unknown";
}
if ($recordlabel = $row['recordlabel']){
$recordlabel = $row['recordlabel'];
}else{
$recordlabel = "Unknown";
}
if ($officialsite = $row['officialsite']){
$officialsite = $row['officialsite'];
}else{
$officialsite = "#";
}
if ($sitename = $row['sitename']){
$sitename = $row['sitename'];
}else{
$sitename = "Unknown";
}
} // End of while statement
}else{
$engname = "Unknown";
$korname = "Unknown";
$engbn = "Unknown";
$korbn = "Unknown";
$dateofbirth = "Unknown";
$occupation = "Unknown";
$debut = "Unknown";
$recordlabel = "Unknown";
$officialsite = "#";
$sitename = "Unknown";
} // End of If statement
// Free result set
//mysqli_free_result($result);
?>
testhub-artistalbum.php
<?php
//connect to db
include "mysqli_connect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['albumpage']))){
$albumpage = 1;
}else{
$albumpage = $_GET['albumpage'];
}
//query for record count to setup pagination
$sqli = "SELECT * FROM albums WHERE soloID = 3";
$album_data = mysqli_query($link, $sqli);
$album_rows = mysqli_num_rows($album_data);
//number of photos per page
$album_pagerows = 4;
//get the last page number
$last_album = ceil($album_rows/$album_pagerows);
//make sure the page number isn't below one, or more than last page num
if ($albumpage < 1){
$albumpage = 1;
}elseif ($albumpage > $last_album){
$albumpage = $last_album;
}
//Set the range to display in query
$max_album = 'limit ' .($albumpage - 1) * $album_pagerows .',' .$album_pagerows;
//get all of the photos
$albumList = "";
$sqli2 = "SELECT * FROM albums WHERE soloID = 3 ORDER BY releasedate DESC $max_album";
$album_sql = mysqli_query($link, $sqli2);
//check for photos
$albumCount = mysqli_num_rows($album_sql);
if ($albumCount > 0){
while($album_rows = mysqli_fetch_array($album_sql)){
$albumID = $album_rows["albumID"];
$albumpic = $album_rows["albumpic"];
$title = $album_rows["albumTitle"];
$releasedate = $album_rows["releasedate"];
$page = $album_rows["page"];
$albumList .= '
<li class="albumthumb">
<img class="profile" src="../albums/album_th/' . $albumpic . '.jpg" alt="' . $albumpic . '" width="120" height="120" border="0" /><p class="datatitle">' . $title . '</p><p class="data-releasedate">' . $releasedate . '</p>
</li>
';
}
}else{
$albumList = "There are no available albums at this time!";
}
//mysql_close();
?>
Sorry for not explaining clearly. I want to be able to use pagination when making a profile page like the url. I want to use the number in the url to change the id (soloID) in the sql code.
Good idea in saving time, right? MySQLi getting easier every time I see it.
Thank you.
Changed 5/31/2012 5:44PM CT
$artist = $_GET['artist_id']
into
if(is_numeric($_GET['artist_id'])){
$artist = $_GET['artist_id'];
}else{
$artist = 1;
}
artist/detail?artist_id=#
You would use detail as the page, (probably have a detail folder with a index) and on the detail page, have a $_GET[] variable somewhere that gets the artist_id. So your code could look something like this:
$artist = $_GET['artist_id']; // Filter this variable
$sql = "SELECT * FROM individuals WHERE soloID = '{$artist}'";
/**
* Verify if the ID exists
* Display query results, etc.
*/
So everytime you change the artist_id variable in the URL, the page should change accordingly.
Welcome to my second favorite language! I love php.
Someone already answered your question, but I have some suggestions.
The code you have isn't vulnerable as is cause the user provided data is passed through math... but inlining variables is a good way to leave yourself open to SQL Injection attacks. Look up bind_param() and prepared statements and get in the habit of using them. Always. Well almost always..
Unfortunately SQL doesn't allow you to bind things like the values you use for LIMIT,ORDER BY,GROUP BY so you have to handle those yourself.
Never trust anything derived from a user, so do the work and check it.
Sort columns should always be column names. Check them.
if ( ! in_array($sort_column,array('column1','column2','column3') ) ) $sort_column = 'column1';
Limits should always be integers. Cast them as such.
$safe_limit = (int) $user_limit;
There is no need to copy the array values into another variable. Just use them directly.
You need to escape your values going into html. Lookup urlencode() and htmlentities().
My IE is up to a gig of memory so I'll have to finish this up later.