Left join for multiple tables - php

I am trying to execute the following MySQL query:
SELECT event.event_id, venue.venue_name, venue.alt_venue_name, venue.venue_address1, venue.cross_street, dictionary_city.city_name, venue.zip, dictionary_filter.filter_name, venue.capacity, event.start_date, event.end_date, dictionary_barType.is_ob, dictionary_barType.barType_name, event.barType_time, event.is_food, event.food_type, event.food_time, dictionary_age.age_name, dictionary_age.age_description, event.ticketCo_id, event.ticket_locator, event.ticket_left, event_description.description, event_highlight.highlight, event.event_tag, event.image_flyer, event.image_flyer_310x425, event.image_2, event.image_2_310x208, event.image_3, event.image_3_310x208
FROM event
LEFT JOIN venue
ON venue.venue_id=event.venue_id
LEFT JOIN dictionary_city
ON venue.city_id=dictionary_city.city_id
LEFT JOIN dictionary_filter
ON venue.venueType_id=dictionary_filter.filter_id
LEFT JOIN dictionary_barType
ON event.barType_id=dictionary_barType.barType_id
LEFT JOIN dictionary_age
ON event.event_age_id=dictionary_age.age_id
LEFT JOIN event_highlight
ON event_highlight.event_id=event.event_id
LEFT JOIN event_description
ON event_description.event_id=event.event_id
WHERE event.event_id="".$event_id."";
When I run the query in PhP Admin it works fine, but when I add the code to my site, I get the following error
"Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in
/home/nye/public_html/theballdrop.com/templates/template.event.php on
line 29 - See more at:
http://theballdrop.com/new-years-eve-madame-tussauds/#sthash.880jgbaa.dpuf"
The query it refers to is "if ($row = mysql_fetch_array($result)){"
I am not sure where to go from here. This is supposed to display information from multiple tables on a single page. $event_id is the variable and a specific event ID would determine the info to display for that specific event page.
please help.
===========================
Here is the entire code for the page:
<?php
// FUNCTION: CONVERT DATE
include (PATH . DIR_INCLUDE . "convert-time.php");
// CONNECT TO NYE DATABASE
include (PATH . DIR_TEMPLATE . "mysql-connect.php");
$sql = "SELECT event.event_id, venue.venue_name, venue.alt_venue_name, venue.venue_address1, venue.cross_street, dictionary_city.city_name, venue.zip, dictionary_filter.filter_name, venue.capacity, event.start_date, event.end_date, dictionary_barType.is_ob, dictionary_barType.barType_name, event.barType_time, event.is_food, event.food_type, event.food_time, dictionary_age.age_name, dictionary_age.age_description, event.ticketCo_id, event.ticket_locator, event.ticket_left, event_description.description, event_highlight.highlight, event.event_tag, event.image_flyer, event.image_flyer_310x425, event.image_2, event.image_2_310x208, event.image_3, event.image_3_310x208 FROM nye_newyears.event LEFT JOIN venue ON venue.venue_id=event.venue_id LEFT JOIN dictionary_city ON venue.city_id=dictionary_city.city_id LEFT JOIN dictionary_filter ON venue.venueType_id=dictionary_filter.filter_id LEFT JOIN dictionary_barType ON event.barType_id=dictionary_barType.barType_id LEFT JOIN dictionary_age ON event.event_age_id=dictionary_age.age_id LEFT JOIN event_highlight ON event_highlight.event_id=event.event_id LEFT JOIN event_description ON event_description.event_id=event.event_id WHERE event.event_id=".$event_id."";
$result = mysql_query($sql, $con);
// START MYSQL QUERY
if ($row = mysql_fetch_array($result)){
// VENUE INFORMATION
$venueName = $row['venue_name']; // OFFICIAL VENUE NAME
$venueName2 = $row['alt_venue_name']; // NAME YOU WANT TO DISPLAY AT TOP OF EVENT PAGE
$venueAddress = $row['venue_address1']; // ADDRESS OF VENUE
$venueCrossStreet = $row['cross_street']; // CROSS STREETS
$venueCity = $row['city_name']; // VENUE CITY
$venueState = $row['state_abb']; // VENUE STATE
$venueZip = $row['zip']; // VENUE ZIP
$venueType = $row['filter_name']; // TYPE OF VENUE
$venueCapacity = $row['capacity']; // CAPACITY OF VENUE
// EVENT INFORMATION
$start = $row['start_date'];
$startDate = convertDate ($start); // START DATE OF EVENT
$startTime = convertTime ($start); // START TIME OF EVENT
$end = $row['end_date'];
$endDate = convertDate ($end); // END DATE OF EVENT
$endTime = convertTime ($end); // END TIME OF EVENT
$ob = $row['is_ob']; // IS THERE OPEN BAR? "YES" OR "NO"
$obType = $row['barType_name']; // TYPE OF OPEN BAR
$obTimes = $row['barType_time']; // OPEN BAR TIMES (START AND END)
$food = $row['is_food']; // IS THERE FOOD? "YES" OR "NO"
$foodType = $row['food_type']; // TYPE OF FOOD SERVED
$foodTimes = $row['food_time']; // TIMES FOOD BEING SERVED (START AND END)
$eventAge = $row['age_name']; // AGE RESTRICTION (IF ANY)
$eventAge_descrip = $row['age_description'];
$ticketCompany = $row['ticketCo_id'];
$ticketID = $row['ticket_locator']; // WIDGET ID
$ticketsLeft = $row['ticket_left']; // TOTAL TICKETS LEFT
$eventDescription = $row['description']; // EVENT DESCRIPTION
$eventHighlight = $row['highlight']; // EVENT HIGHLIGHT
$eventTag = $row['event_tag']; // EVENT LISTING DESCRIPTION
// EVENT IMAGES
$flyer = $row['image_flyer']; // FULL SIZE EVENT FLYER IMAGE
$flyer_310x425 = $row['image_flyer_310x425']; // FLYER IMAGE - 310x425
$image2 = $row['image_2']; // FULL SIZE IMAGE 2
$image2_310x208 = $row['image_2_310x208']; // IMAGE 2 - 310x208
$image3 = $row['image_3']; // FULL SIZE IMAGE 3
$image3_310x208 = $row['image_3_310x208']; // IMAGE 3 - 310x208
}
// VENUE MAP
$venueMap ="$venueAddress+$venueCity+$venueState+$venueZip" ;
// CLOSE DATABASE
mysql_close($con);
// INCLUDE GLOBAL HEADER
include (PATH . DIR_INCLUDE . "site-header.php");
?>
<body>
<?php include_once(PATH . "analyticstracking.php") ?>
<div id="wrapper">
<?php include (PATH . DIR_INCLUDE . "header.php"); ?>
<div class="row">
<div class="middle">
<div class="wrapper event-header">
<div class="left twoThird slogan"> <br />
<h1>
<?=$venueName2?>
</h1>
<h5>
<?=$eventTag?>
</h5>
</div>
<div class="left oneThird last"> <a class="buy-now" href="#tickets" ><span>Buy Now</span></a> Ask a Question </div>
<!-- End: button -->
</div>
</div>
<!--End .middle -->
<div class="wrapper">
<div class="twoThird left columns">
<div class="roundCorner">
<div class="widget data flier-section">
<div class="flier left"> <img src="<?=DIR_IMAGES?><?=$flyer_310x425?>" alt="<?=$venueName2?> New Years Eve 2014" width="310" height="425" /> </div>
<!-- End # left-->
<div class="photos right"> <img src="<?=DIR_IMAGES?><?=$image2_310x208?>" alt="<?=$venueName?> Times Square New Years Eve 2014" /> <img src="<?=DIR_IMAGES?><?=$image3_310x208?>" alt="<?=$venueName?> Times Square New Years Eve" /> </div>
<!-- End # right slider-->
</div>
<!-- End # widget-->
<div class="center detail">
<div class="widget lightgray-base">
<h3 class="widget-heading">Why We Recommend</h3>
<ul class="blist">
<?=$eventHighlight?>
</ul>
</div>
<div class="widget">
<h3 class="headingbar">Overview</h3>
<?=$eventDescription?>
<p><strong>About your Tickets: </strong> (1) Show up early and help reduce the wait time, (2) Make sure to have your physical ticket on hand because you will need to show it to NYPD and security upon request, (3) You accept the risks and agree to adhere to the NYPD rules and regulations for the evening, (4) If you select shipping as your delivery method, tickets will not be sent out until December, (5) A LIVE VIEW of The Ball Drop is not guaranteed. Large crowds should be expected</p>
</div>
</div>
</div>
<!-- End of main-->
<div class="roundCorner"> <a name="tickets" ></a>
<h3 class="widget-heading">Purchase Tickets
<div class="info">Have a Question? Call 212.201.0735 or email info#balldrop.com </div>
</h3>
<div class="widget data">
<p>
<?php
if ($ticketCompany == 1){
// START: CRAVE TICKETS WIDGET -->
echo "<iframe scrolling='auto' frameborder='0' width='99.5%' height='600' src='http://cravetickets.com/widgets/iframe/qU4owWdNmYt/".$ticketID."' ></iframe>";
// END: CRAVE TICKETS WIDGET -->
} else if ($ticketCompany == 2){
// START: LAUGHSTUB TICKET WIDGET -->
echo "<script type='text/javascript' src='http://www.laughstub.com/embed/cart/index.cfm?showTimingID=".$ticketID."&bgcolor=E53D23&fontcolor=ffffff&&brand=ticketmob&displayTitle=no&affiliate=1087&checkout=pmtix'></script>";
// END: LAUGHSTUB TICKET WIDGET -->
}
?>
</p>
<p><strong> Price increase warning:</strong> New Year's Eve ticket prices often go up significantly (100% +) the closer you get to New Years Eve. Also note that many NYE Events will sell out well in advance of New Years Eve. </p>
</div>
</div>
</div>
<!-- End # twoThird-->
<div class="oneThird sidebar last">
<div class="roundCorner lightgray-base">
<h3 class="widget-heading">What to know</h3>
<div class="box data">
<h4>Share This Event</h4>
<p> <span class='st_facebook_large' displayText='Facebook'></span> <span class='st_twitter_large' displayText='Tweet'></span> <span class='st_plusone_large' displayText='Google +1'></span> <span class='st_linkedin_large' displayText='LinkedIn'></span> <span class='st_pinterest_large' displayText='Pinterest'></span> <span class='st_email_large' displayText='Email'></span> </p>
<ul class="know-list">
<li>
<h5>START TIME</h5>
<h4>
<?=$startDate?>
at
<?=$startTime?>
</h4>
</li>
<li>
<h5>END TIME</h5>
<h4>
<?=$endDate?>
at
<?=$endTime?>
</h4>
</li>
<li>
<h5>ADDRESS</h5>
<h4>
<?=$venueAddress?>
<br>
<?=$venueCrossStreet?>
</h4>
</li>
<li>
<h5>VENUE TYPE</h5>
<h4>
<?=$venueType?>
</h4>
</li>
<li>
<h5>AGE REQUIREMENT</h5>
<h4>
<?=$eventAge?>
<br />
<?=$eventAge_descrip?>
</h4>
</li>
<li>
<h5>CAPACITY</h5>
<h4>
<?=$venueCapacity?>
</h4>
</li>
<li>
<h5>OPEN BAR</h5>
<h4>
<?=$ob?>
|
<?=$obType?>
<br />
from
<?=$obTimes?>
</h4>
</li>
<li>
<h5>FOOD SERVED</h5>
<h4>
<?=$food?>
|
<?=$foodType?>
<br />
from
<?=$foodTimes?>
</h4>
</li>
</ul>
</div>
</div>
<!-- End of roundCorner -->
<div class="roundCorner lightgray-base">
<h3 class="widget-heading">Map</h3>
<div class="box"> <img src="http://maps.googleapis.com/maps/api/staticmap?center=<?=$venueMap?>&zoom=16&size=295x245&markers=size:mid%7Ccolor:red%7C<?=$venueMap?>&sensor=false">
<div class="address"> <br />
<h3>
<?=$venueName?>
</h3>
<h5>
<?=$venueAddress?>
<br />
<?=$venueCrossStreet?>
<br />
<?=$venueCity?>
,
<?=$venueState?>
<?=$venueZip?>
</h5>
</div>
</div>
</div>
<!-- End of roundCorner -->
<div class="banner-300"> <img class="fullWidth" src="<?=DIR_IMAGES?>banner-300.jpg"> </div>
<!-- End # Banner-->
</div>
<!-- End of onethird-->
</div>
<!-- End # wrapper-->
<div id="footer-top">
<!-- START: SIMILAR PARTIES -->
<div class="listing-wrapper">
<h2 class="subHeading">We Recommend More NYE Parties <strong>›</strong> </h2>
<ul class="columns">
<?php include (PATH . DIR_INCLUDE . "similar-parties.php"); ?>
</ul>
</div>
<!-- END: SIMILAR PARTIES -->
</div>
<!-- End # footer-top -->
<?php include (PATH . DIR_INCLUDE . "footer.php"); ?>
</div>
<!-- End # row-->
</div>
<!-- End # wrapper-->
</body>
</html>

Add database selection to your connect script, like so:
<?php
$hostname = "localhost";
$username = "{username]";
$password = "[pass]";
$dbname = "nye_newyears";
$con = mysql_connect("$hostname", "$username", "$password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($dbname)) {
die('Could not find or access database ' . $dbname);
}
?>

event is a keyword in mysql. so wrap it inside quotes (`) and try.
echo your $sql in browser copy it and paste it in phpmyadmin and execute, you will get the particular error if any.

At first, check your MySql Table name in server. Sometimes some hosts add a prefix on table name.
You should check $result object first like
if(!$result){
exit(mysql_error());
}else{
if ($row = mysql_fetch_array($result)){
// ....
// ...
}
}

Thank you all for your help. Knittl you were RIGHT!!!
I added the following code to mysql-connect file:
if(!mysql_select_db($dbname)) {
die('Could not find database ' . $dbname);
}
everything works now.
Thank you so much.

Related

Pagination and category not working together

Okay, so I got this site im working on to better myself with php, And I got a category system working in a switch and also a pagination, but i can't really get it to work together.
What I got so far graps all 4 posts from my DB and displays it on the "blog.php" page with the pagination making it only show 1 result at a time, blog.php?page=2 showing the next and so on, and it all works great.
Now clicking on the category "test" will display 2 results on the page "blog.php?category=2", still showing 1 by the pagination, but clicking on the next page "blog.php?category=2?page=2" will cause it to give the warnings
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\rusting\blog.php on line 284
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\rusting\blog.php on line 325
The code i got is this
<?php switch($category):
case 0: ?>
<?php
//Fetch from database first 1 items which is its limit. For that when page open you can see first 10 items.
$query=mysqli_query($db,"
SELECT blog.id, blog.title, blog.date, blog.content, blog.image, blog.author_id, blog.category, blog.short_desc, category.id, category.name
FROM blog
INNER JOIN category
ON blog.category=category.id
ORDER BY blog.id DESC
LIMIT $start, $limit
");
//print 1 items
while($result=mysqli_fetch_array($query))
{
echo "
<!-- Begin Post -->
<div class='post'>
<!-- Begin Post Info -->
<div class='post-info'>
<!-- Begin Date -->
<div class='post-date'> <span class='day'>15</span> <span class='month'>FEB</span> <span class='year'>2011</span> </div>
<!-- End Date -->
<!-- Begin Title -->
<div class='post-title'>
<h1><a href='post.php?id=".$result['id']."'>
".$result['title']."
</a></h1>
<div class='post-meta'> <span class='comments'>13 Comments</span> <span class='categories'><a href='#'>".$result['name']."</a></span> </div>
</div>
<!-- End Title -->
</div>
<!-- End Post Info -->
<div class='post-text'>
<div class='post-img'><a href='post.php?id=".$result['id']."'><img src='style/images/blog/".$result['image']."' alt='' /></a></div><br/>
<p>".$result['short_desc']." <a class='more' href='post.php?id=".$result['id']."'>Læs mere →</a></p>
</div>
<!-- End Text -->
</div>
<!-- End Post -->
";
}
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($db,"select * from blog"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
?>
<br><br><br><br>
<?php if($page>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo "<li><a href='?page=".($page-1)."' class='button'>PREVIOUS</a></li>";
}
if($page!=$total)
{
////Go to previous page to show next 10 items.
echo "<li><a href='?page=".($page+1)."' class='button'>NEXT</a></li>";
}
?>
<br><br><br><br>
<div class="page-navi">
<ul>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$page) { echo "<li><a class='current'>".$i."</a></li>"; }
else { echo "<li><a href='?page=".$i."'>".$i."</a></li>"; }
}
?>
</ul>
</div>
<?php break;?>
<?php case $category: ?>
<?php
//Fetch from database first 1 items which is its limit. For that when page open you can see first 10 items.
$query=mysqli_query($db,"
SELECT blog.id, blog.title, blog.date, blog.content, blog.image, blog.author_id, blog.category, blog.short_desc, category.id, category.name
FROM blog
INNER JOIN category
ON blog.category=category.id
WHERE category=".$category."
ORDER BY blog.id DESC
LIMIT $start, $limit
");
//print 1 items
while($result=mysqli_fetch_array($query))
{
echo "
<!-- Begin Post -->
<div class='post'>
<!-- Begin Post Info -->
<div class='post-info'>
<!-- Begin Date -->
<div class='post-date'> <span class='day'>15</span> <span class='month'>FEB</span> <span class='year'>2011</span> </div>
<!-- End Date -->
<!-- Begin Title -->
<div class='post-title'>
<h1><a href='post.php?id=".$result['id']."'>
".$result['title']."
</a></h1>
<div class='post-meta'> <span class='comments'>13 Comments</span> <span class='categories'><a href='#'>".$result['name']."</a></span> </div>
</div>
<!-- End Title -->
</div>
<!-- End Post Info -->
<div class='post-text'>
<div class='post-img'><a href='post.php?id=".$result['id']."'><img src='style/images/blog/".$result['image']."' alt='' /></a></div><br/>
<p>".$result['short_desc']." <a class='more' href='post.php?id=".$result['id']."'>Læs mere →</a></p>
</div>
<!-- End Text -->
</div>
<!-- End Post -->
";
}
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($db,"select * from blog WHERE category=".$category.""));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
?>
<br><br><br><br>
<?php if($page>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo "<li><a href='?category=".$category."?page=".($page-1)."' class='button'>PREVIOUS</a></li>";
}
if($page!=$total)
{
////Go to previous page to show next 10 items.
echo "<li><a href='?category=".$category."?page=".($page+1)."' class='button'>NEXT</a></li>";
}
?>
<br><br><br><br>
<div class="page-navi">
<ul>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$page) { echo "<li><a class='current'>".$i."</a></li>"; }
else { echo "<li><a href='?category=".$category."?page=".$i."'>".$i."</a></li>"; }
}
?>
</ul>
</div>
<?php break;?>
<?php endswitch;?>
Okay, it was pretty simple and i can't believe i didn't realize this earlier. I just needed to change the link generated for it to work.
I was trying to visit page 2 on category 2 with "blog.php?category=2?page=2"
For it all to work i just needed to change it to "blog.php?category=2&page=2"

php form submit isnt inserting into the database

Right, this should be very basic php, however i cannot for the life of me figure out why this is not working.
I have a form which when submit it should grab the fields then insert the data into the database. I have on my index.php a section which actually pulls back info from database and works fine so i cant see this being a connection problem.
db_connection.php i have hashed out the info here as its for my database, but everything is correct
<?php
define("DB_SERVER","**********");
define("DB_USER","*************");
define("DB_PASS","*********");
define("DB_NAME","reviews");
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
if(mysqli_connect_errno()){
die("database connection failed");
}
?>
functions.php
<?php
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
function confirm_query($result){
if(!$result){
die("database query failed");
}
}
function find_reviews($connection){
$query = "SELECT * ";
$query .= "FROM reviews";
$result = mysqli_query($connection,$query);
confirm_query($result);
while($reviews = mysqli_fetch_assoc($result)){
$output = "<li class=\"first\">";
$output .= $reviews["name"];
$output .= "</li>";
$output .= "<li class=\"second\">";
$output .= $reviews["company"];
$output .= "</li>";
$output .= "<li class=\"third\">";
$output .= $reviews["comment"];
$output .= "</li>";
$output .= "<li class=\"line\"></li>";
echo $output;
}
mysqli_free_result($result);
return $reviews;
}
?>
index.php
to note with this, the function find_reviews() works and does grab the information from database. Also the above "db_connection.php" and "functions.php" are required in index.php
<?php
require("includes/header.php");
$page_title = "All County Road Markings";
$description = "Specialising in Road Marking & Car Park Lining. We are a professional established road marking service with over 20 years experience";?>
<?php require("includes/db_connection.php"); ?>
<?php require("includes/functions.php"); ?>
<?php if(isset($_POST["submit"])){
$name = $_POST["name"];
$company = $_POST["company"];
$comment = $_POST["comment"];
$query = "INSERT INTO `reviews` (name,company,comment) VALUES ('$name','$company','$comment')";
$result=mysqli_query($connection,$query);
confirm_query($result);
redirect_to("index.php");
}
?>
<div id="banner"></div>
<div id="paragraph">
<h2>All County Road Markings are a professional established road marking<br>service with over 20 years experience within the industry</h2>
<hr style="width: 1050px;">
</div>
<div id="content">
<div id="left">
<div class="slot">
<div class="top carpark"> </div>
<div class="linkbar">
<h1>Car Parks</h1>
</div><div class="linktext">
<ul class="comments display">
<li>- Car Parking Bays</li>
<li>- Disabled Parking Bays</li>
<li>- Parent and Child Bays</li>
<li>- Lettering</li>
<li>- Hatchings</li>
<li>- Arrows</li>
<li>- Customised Lettering</li>
</ul>
</div>
</div>
<div class="slot">
<div class="top roadmark"> </div>
<div class="linkbar">
<h1>Road Markings</h1>
</div>
<div class="linktext">
<ul class="comments display">
<li>- Hatchings</li>
<li>- Centre Lines</li>
<li>- Double Yellow lines</li>
<li>- Give way junctions</li>
<li>- Reinstatement of existing markings</li>
</ul>
</div>
</div>
<div class="slot">
<div class="top sportcourt">
</div>
<div class="linkbar">
<h1>Sports/Playground Court</h1>
</div>
<div class="linktext">
<ul class="comments display">
<li>- Tennis Court</li>
<li>- Basketball Court</li>
<li>- 5 A side Court</li>
<li>- Netball Court </li>
<li>- Reinstatement of existing markings</li>
<li>- Custom designs available</li>
</ul>
</div>
</div>
</div>
<div id="right">
<div id="rightbar">
<h2 style="color: white;">Testimonials</h2>
</div>
<div id="comment">
<ul class="comments">
<?php echo find_reviews($connection); ?>
</ul>
</div>
<div id="write">
<p style="margin: 0px; padding-top: 5px;color: grey; font-size: 1.25em;">Click to write a review...<p>
</div>
</div>
<div id="quote"><div class="link-text">contact us</div></div>
</div>
<div id="add">
<div id="close"></div>
<form action="index.php" method="POST">
<div id="name"> Name:<br/><span>Please Enter Full Name</span>
<input type="text" name="name" id="textbox">
</div>
<div id="company"> Company<br/><span>Please Enter Company Name</span>
<input type="text" name="company" id="textbox1">
</div>
<div id="review"> Review<br/><span>Please Enter Review</span>
<textarea name="comment" id="reviewComment"></textarea>
</div>
<div id="save">
<input type="submit" name="submit">
</div>
</form>
</div>
</body>
</html>
ok so can anyone see anything that i am doing wrong? as when the form is submitted it is just not inserting into the database.
EDIT::
when i try echo mysqli->error; i get following error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';' in /hermes/bosoraweb140/b484/ipg.allcountyroadmarking/index.php on line 17
So i changed it to
if(!results){
echo "hello";
}
and i do not see the "hello" so it is indicating that i am not even getting into the part that it deals with the post fields
SELF RESOLVED:::::
Ive fixed it, i changed action="index.php" to action=""
i dont understand, it should have worked , but for some reason having the action blank worked. both should be acceptable !
The if statement for $_POST['submint'] might be false on every submit. Maybe try !empty($_POST)
The form action which was set to
<form action="index.php" method="POST">
did not work, however i do not see why not as it is referencing the current page.
However changing it to this resolved the problem.
<form action="" method="POST">
Well you got the php in the same file so that maybe why the action="" is working if it defaults to the same page.. action="index.php" should prepend the current web address. Maybe try putting the full web address in the action="the url for index.php" to see if that works. If does then action="index.php" must not be going to the right file.

How to display mysql array with limit together with PHP

I have a mysql query together with my html code looking like this.
<?php
/////////////////////////////////////////////////////////////
// RANDOM USER DISPLAYED WHICH MATCHS
/////////////////////////////////////////////////////////////
$statement = $dbConn->prepare("SELECT user_name, profile_image_url, user_age, country FROM users WHERE profile_image = '2' AND gender = ? ORDER BY RAND() LIMIT 2;");
$statement->execute(array($logged_in_user['searching_for']));
$random_match= $statement->fetch(PDO::FETCH_BOTH);
/////////////////////////////////////////////////////////////
// END OF RANDOM QUESTIONS
/////////////////////////////////////////////////////////////
?>
<div id="front_match">
<div class="front_box">
<div class="front_box_left">
<div style="position: relative;">
<img src="images/woman_1.jpg" style="max-width:100%;height:auto;">
<div class="transparent">Information about user one comes here</div>
</div>
</div>
<div class="front_box_right">
<div style="position: relative;">
<img src="images/woman_2.jpg" style="max-width:100%;height:auto;">
<div class="transparent">Information about user two comes here</div>
</div>
</div>
</div> <!-- div box finished here -->
</div> <!-- div match finished here -->
How to i insert information received from the database in
"Information about user one" and then "Information about user two"?
You can see that i'm using limit 2 so i want to display 1 results in one place and second result in second place
Cheerz
You can still use fetch_array to achieve your goal. Store it in an array, then you can call it whenever you want.
while($statement->fetch()){
$user_name_arr[] = $user_name;
$user_age_arr[] = $user_age;
/* ... REST OF CODE ... */
}
Then call them manually:
<div id="front_match">
<div class="front_box">
<div class="front_box_left">
<div style="position: relative;">
<img src="images/woman_1.jpg" style="max-width:100%;height:auto;">
<div class="transparent">
<?php
echo "Name: ".$user_name_arr[0];
echo "Age: ".$user_age_arr[0];
/* ECHO REST OF THE INFORMATION */
?>
</div>
</div>
</div>
<div class="front_box_right">
<div style="position: relative;">
<img src="images/woman_2.jpg" style="max-width:100%;height:auto;">
<div class="transparent">
<?php
echo "Name: ".$user_name_arr[1];
echo "Age: ".$user_age_arr[1];
/* ECHO REST OF THE INFORMATION */
?>
</div>
</div>
</div>
</div> <!-- div box finished here -->
</div> <!-- div match finished here -->
Just wondering:
I'm just wondering, why do you have to separate them and not use while loop. And just go with this:
<div id="front_match">
<div class="front_box">
<?php
while($statement->fetch()){
?>
<div class="front_box_left">
<div style="position: relative;">
<img src="<?php echo $profile_image_url; ?>" style="max-width:100%;height:auto;">
<div class="transparent">
<?php
echo "Name: ".$user_name;
echo "Age: ".$user_age;
/* ECHO REST OF THE INFORMATION */
?>
</div>
</div>
</div>
<?php
} /* END OF WHILE LOOP */
?>
</div> <!-- div box finished here -->
</div> <!-- div match finished here -->
You want excatly two rows? Then fatch two times:
$first_match = $statement->fetch(PDO::FETCH_BOTH);
$second_match = $statement->fetch(PDO::FETCH_BOTH);
You can use $first_match for the first table and $secon_match for the second table.

"if message/text exists in database", then show the message that the user created from latest to oldest

I'm working on this message system. The user has a form presented to him, where the user will type notes, in this case called a "message". When the user visits his profile page, he is shown the message that he had typed in the form earlier and pressed saved.
Screenshot:
http://i.stack.imgur.com/VEsDg.png
My database has a table called "messages" where I have columns pid, uid, message, time, and picture where the uid is the uid in my "users" table.
So the pid is a auto-incrementing and the uid is the user id of the user who posted the message.
(The user posts a URL to his picture in the form which is later saved to the picture column in the database.
My PHP code where I get data from the database:
<?php
$uid = $this->session->userdata('uid');
$this->db->limit(10); //Use this to limit the entires while you show the entires on the front page.
$query = $this->db->query("SELECT pid, message, time, picture FROM messages WHERE uid = '$uid';");
foreach ($query->result_array() as $row)
{
$message = $row['message'];
$time = $row['time'];
$picture = $row['picture'];
}
?>
My html code in my profile_body.php page in my views folder where I have the above's code included.
<div class="list-group list-group-breakout">
<a class="list-group-item" href="https://assembly.com/assemblycoins">
<div class="chip">
<div class="chip-icon">
<img alt="Coins" width="48" height="48" class="app-icon" src="<?php echo $picture ?>"/>
</div>
<div class="row">
<div class="col-sm-12">
<p class="omega"><?php echo $message;?></p>
</div>
<div class="col-sm-12 right-align">
<p class="gray-2 small omega">
Feb. 21, 2015 <!-- Not from database -->
</p>
</div>
</div>
</div>
How would I get only 10 results for the messages that the users typed in the database and display it? I have tried to paste the same html code again but it displays the same message and picture.
Thanks.
Here is some improvements to do :
$uid = $this->session->userdata('uid');
$result = $this->db->select('pid, message, time, picture')
->where(array('uid' => $uid))
->limit(10)
->get('messages')
->result_array();
$this->load->view('profile_body', $result);
In your view profile_body.php file :
<?php foreach($result as $row): ?>
<div class="list-group list-group-breakout">
<a class="list-group-item" href="https://assembly.com/assemblycoins">
<div class="chip">
<div class="chip-icon">
<img alt="Coins" width="48" height="48" class="app-icon" src="<?php echo $row['picture'] ?>"/>
</div>
<div class="row">
<div class="col-sm-12">
<p class="omega"><?php echo $row['message'];?></p>
</div>
<div class="col-sm-12 right-align">
<p class="gray-2 small omega">
Feb. 21, 2015 <!-- Not from database -->
</p>
</div>
</div>
</div>
<?php endforeach; ?>

Setting $_SESSION as result from MySQL Query

I'm trying to create a script that logs you in and creates a session using a set usercode in the same table as my usernames.
Each usercode is different to each username as each usercode will display different data on my index.php
I am using the following code to authenticate my users and assign their usercodes:
<?php
include ("include/dbConfig.php");
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect($db_hostname, $db_username, $db_password)or die("cannot connect"); // no quotes needed around vars
mysql_select_db($db_database)or die("cannot select DB"); // no quotes needed around vars
$username = mysql_real_escape_string($_POST['username']);
$encrypted_password = mysql_real_escape_string(md5($_POST['password']));
$sql="SELECT username, password FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$sql2="SELECT usercode FROM $tbl_name WHERE usercode='$usercode'";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$sql2= $usercode1['usercode'];
// If result matched $username and $password, table row must be *AT LEAST* 1 row
if(mysql_num_rows($result)){
session_start();
$_SESSION['isamsdata']->UserCode) != ''; //This needs fixing - array
header("Location: index.php?logged in successfully");
} else {
header("Location:login.php?msg=email or password wrong");
}
?>
My index.php:
<?php
error_reporting(E_ALL);
session_start();
//$_SESSION['isamsdata']->UserCode = 'test';
unset($_SESSION['child_id']);
unset($_SESSION['child_first_name']);
require_once('include/newuserfunction.php');
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
include "header.php";
include "topmenu.php";
include "leftmenu.php";
?>
<?php
include 'helpBox.php';
?>
<!-- BEGIN PAGE -->
<div class="page-content">
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<!-- BEGIN PAGE TITLE & BREADCRUMB-->
<h3 class="page-title">
Parent Dashboard
<small>This is your dashboard.</small>
<button class="btn orange" style="float: right; width: 150px;" id="addpupil" onclick="showhidepupilbox();" >Add Pupil</button>
</h3>
<ul class="breadcrumb">
<li>
<i class="icon-home"></i>
Home
<i class="icon-angle-right"></i>
</li>
<li>Dashboard</li>
<!--<button style="float: right; background-color:green; color: white !important; margin: -1px 9px 0px 0px; border: none;" onclick="addChild();">Add Child</button>-->
</ul>
<!-- END PAGE TITLE & BREADCRUMB-->
</div>
</div>
<?php
if(isset($_GET['status']))
{
if($_GET['status'] == 1) {
echo '<div class="alert alert-success">
<button class="close" data-dismiss="alert"></button>Pupil Added Successfully. </div>';
} else {
echo '<div class="alert alert-error">
<button class="close" data-dismiss="alert"></button>Pupil Not Added Successfully. </div>';
}
}
?>
<div class="row-fluid" id="addpupilform" style="display: none;" >
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Add Pupil</h4>
</div>
<div class="portlet-body">
<div class="portlet-body form">
<form action="insert-child.php" id="add_user" class="form-horizontal add_user" method="post" name="childform">
<div class="alert alert-error hide">
<button class="close" data-dismiss="alert"></button>
You have some form errors. Please check below. </div>
<div class="alert alert-success hide">
<button class="close" data-dismiss="alert"></button>
Your form validation is successful! </div>
<div class="control-group">
<label class="control-label">First Name<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="first_name" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="last_name" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date Of Birth<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="dob" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="form-actions" style=" padding-left: 12px;">
<button type="submit" class="btn orange" >Add</button>
</div>
</form>
<!--- close body-form-->
</div>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="clearfix"></div>
<div class="rows">
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Pupil's Details</h4>
</div>
<div class="portlet-body">
<!--<div class="scroller" style="height: 300px;" data-always-visible="1" data-rail-visible="0">-->
<div class="portlet-body">
<?php if(getUserChilds($_SESSION['isamsdata']->UserCode) != '') { ?>
<table class="table table-striped table-bordered table-hover" id="sample_2">
<thead>
<tr>
<th >First Name</th>
<th>Last Name</th>
<th>Date Of Birth</th>
<th>Change Details</th>
<th>Progress</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
echo getUserChilds($_SESSION['isamsdata']->UserCode);
?>
</tbody>
</table>
<?php } else { ?>You have not setup any pupil account currently, please fill the form by clicking the Add Pupil icon above.<?php } ?>
</div>
</div>
<!-- scroller </div>-->
</div>
</div>
<!-- End Rows-->
</div>
<!-- Close Div span12-->
</div>
<!-- Close Row-span12 -->
</div>
<!-- Close Row-fluid -->
<div class="row-fluid">
<div class="span12">
<div class="clearfix"></div>
<div class="rows">
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Welcome Parent</h4>
</div>
<div class="portlet-body">
<!--<div class="scroller" style="height: 300px;" data-always-visible="1" data-rail-visible="0">-->
<div class="portlet-body">
Dear <i><?php echo $_SESSION['parentdetails']->title;?> <?php echo $_SESSION['parentdetails']->firstName;?> <?php echo $_SESSION['parentdetails']->surname;?>,</i><br><br>
<p>
A very warm welcome to the on-line joining forms and thank you so much for logging on. We know there's a lot to do here but we hope that completing these on-line forms will be relatively easy and stress-free. Simply enter the name of your son or daughter above by clicking on the ‘add pupil’ tab at the top right hand corner of this page and then click ‘Fill form’.
</p>
<p>
The fields which contain a red asterisk symbol must be completed. All updates to the forms are automatically saved so you can return to the on-line joining forms at any time to complete your submissions.
</p><p>
We recommend that you have a copy of the new parents' Joining Booklet in front of you whilst completing these forms. Don't worry if you haven't, because you can access a PDF of the Joining Booklet 2014 here. Information and help icons are available on all the forms in case you need guidance and, if you are still stuck, please do not hesitate to call the Admissions Office on 000000000.
</p><p>
As well as the forms, we would be very grateful if you could upload a picture of your son/daughter when prompted (this does not have to be a passport photo) and also a copy of the main page of your son or daughter's passport with all their details on it. If you do not have access to a scanner, then please feel free to send in a photocopy to Name, Registrar, at the usual School/College address.
</p><p>
I should also remind you that we do require the following to be posted in hard-copy back to the School/College:</p><p>
<ul style="width: 80%;">
<li>The Medical Forms (required) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
<li>The Direct Debit Form (if appropriate) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
<li>The Gift Aid Form (if appropriate) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
</ul></p><p>
All forms should be completed by Monday 16th June. The information provided on these forms will be processed lawfully and fairly and held for our management and administrative purposes only.
</p><p>
I do hope that you all remain as excited about September as we are, and we look forward to seeing you all soon.
</p><p>
With best wishes,
</p><p>
Name here<br>
Director of Admissions
</p> </div>
</div>
<!-- scroller </div>-->
</div>
</div>
<!-- End Rows-->
</div>
<!-- Close Div span12-->
</div>
<!-- Close Row-span12 -->
</div>
<!-- Close Row-fluid -->
</div>
</div>
<!-- END PAGE CONTAINER-->
</div>
<!-- END PAGE CONTAINER-->
</div> <!-- END PAGE -->
<?php
include "footer.php";
} else {
header("Location:login.php");
}
?>
<script>
function showhidepupilbox()
{
console.log('Check');
jQuery('#addpupilform').toggle();
}
jQuery(document).ready(function() {
jQuery('#addpupilform').hide();
jQuery('#addpupil').click(function(){
console.log('sdf');
jQuery('#addpupilform').toggle();
});
App.setPage("table_managed"); // set current page
App.init(); // init the rest of plugins and elements
});
jQuery(document).ready(function() {
App.setPage("form_validation"); // set current page
App.init(); // init the rest of plugins and elements
});
jQuery(document).ready(function() {
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
I'm quite new to PHP and SQL so any corrections would be respected!
If any database structures are needed, please ask.
What can be improved / needs fixing:
You are using mysql_, which is depreciated since php 5.5 and shouldn't be used any more. Since you are new to php, now is the right time to learn PDO or mysqli_!
You are using md5, which shouldn't be used any more.
And:
session_start();
needs to be the first line in all files that make use of session.
I guess you are using a tutorial that you have found - which is the right way, but I recommend finding another one.
I haven't fixed the md5 issue, because your passwords need to be changed in DB and the script wouldn't work if I did - but change it to mcrypt
I wrote a comment in the code - variable $usercode isn't set, I don't know where it's comming from, you might want to include usercode in the first query/do both together.
Here is your file writen with PDO:
<?php
session_start();
include('include/.db_def.php');
try {
$connection = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE , USER_ONE, PASS_ONE);
$state = $connection->prepare("SELECT username, password FROM users WHERE username = :names AND password = :password");
$state->execute(array('names' => $_POST['username'], 'password' => md5($_POST['password'])));
list ($user,$password)=$state->fetch(PDO::FETCH_NUM);
$state->closeCursor();
$state2 = $connection->prepare("SELECT usercode FROM users WHERE usercode= :usercode");
$state2->execute(array('usercode' => $usercode)); //<<< $usercode isn't set, you need to fix this
list($usercode)=$state2->fetch(PDO::FETCH_NUM);
$state2->closeCursor();
unset($connection);
if (isset($usercode) AND $usercode != '')
{
$_SESSION['isamsdata'] = $usercode;
header("Location: index.php?logged in successfully");
exit();
}
else {
header("Location:login.php?msg=email or password wrong");
exit();
}
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
Your .db_def.php should look like this:
define('HOST_ONE','your host');
define('USER_ONE','db_user');
define('PASS_ONE','db_pass');
define('DB_ONE','db');
SIDENOTE:
I suppose usercode is in the users table? If so, change the query to:
$state = $connection->prepare("SELECT username, password, usercode FROM users WHERE username = :names AND password = :password");
and the part after list to:
list ($user,$password,$usercode)=$state->fetch(PDO::FETCH_NUM);
You can then get rid of the second query!
Here is the complete code with only one query:
<?php
session_start();
include('include/.db_def.php');
try {
$connection = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE , USER_ONE, PASS_ONE);
$state = $connection->prepare("SELECT username, password, usercode FROM users WHERE username = :names AND password = :password");
$state->execute(array('names' => $_POST['username'], 'password' => md5($_POST['password'])));
list ($user,$password,$usercode)=$state->fetch(PDO::FETCH_NUM);
$state->closeCursor();
unset($state,$connection);
if (isset($usercode) AND $usercode != '')
{
$_SESSION['isamsdata'] = $usercode;
header("Location: logged_in.php?logged in successfully");
exit();
}
else {
header("Location:login.php?msg=email or password wrong");
exit();
}
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
?>
Your next pages should start like this:
<?php
session_start();
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
// user seems to be logged in, do whatever you want here
}
else
{
header("Location:login.php?msg=you_are_not_logged_in");
exit();
}
File structure I would recommend:
Create a folder "views"
in views, put this .htaccess file:
<Files ~ "\.(htaccess|php)$">
order allow,deny
deny from all
</Files>
in your root folder, put the file I wrote above and name it index.php, and create the following file for every file you want to run, for the start, name it logged_in:
<?php
session_start();
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
include('views/logged_in.php'); //here you put the file you want to run
}
else
{
header("Location:login.php?msg=not_logged_in");
exit();
}
Now, all the files you want to run will have to be in the 'views' folder, but you allways link to the file in your root folder. You need to create two files with the same name(makes it easier), one in root, one in views. In root, the file should contain the line
include('views/index.php');
but changed to the file you want to run, f.e.
include('views/dashboard.php');
Now create the file logged_in.php in "views" and just put
<?= "HELLO"; ?>
into it, just to see if it's running.
$sql2="SELECT usercode FROM $tbl_name WHERE usercode='$usercode'"
Variable $usercode is undefined
$sql2= $usercode1['usercode'];
Variable $usercode1 is undefined and code is very strange
$_SESSION['isamsdata']->UserCode) != '';
This code is strange. If you want compare it then you should use operator if
I recommended you turn full error reporting and turn on errors output. You can make this by PHP settings in php.ini or in your code.
For example in begin of script
error_reporting(E_ALL);
ini_set("display_errors", 1);
You can do like follwing code:
<?php
session_start();
include ("include/dbConfig.php");
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect($db_hostname, $db_username, $db_password)or die("cannot connect"); // no quotes needed around vars
mysql_select_db($db_database)or die("cannot select DB"); // no quotes needed around vars
$username = mysql_real_escape_string($_POST['username']);
$encrypted_password = mysql_real_escape_string(md5($_POST['password']));
$sql="SELECT usercode FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$result=mysql_query($sql);
// If result matched $username and $password, table row must be *AT LEAST* 1 row
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$usercode= $row['usercode'];
if($usercode!=''){
$_SESSION['isamsdata']->UserCode= $usercode;
header("Location: index.php?logged in successfully");
} else {
header("Location:login.php?msg=email or password wrong");
}
}
?>

Categories