I'm trying to show all the platforms in the "area" and "block_number" which is passed to my page in the url. However when I run the page with the "area" and "block_number" in the url I am not getting any rows. I only get the else statement Sorry No Results. Can someone please show me what I'm doing wrong?
<?
//// Get items from url
$area1 = $_GET[area];
$block_number1 = $_GET[block_number];
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT * from platform_locations where area = $area1 and block_number = $block_number1';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<div class="col-lg-4 col-md-4 col-sm-6 wow bounceInUp" data-wow-duration="1s" data-wow-delay="0.4s">
<div class="feature-1 box-shadow">
<img src="img/platform_icon.png" alt="">
<h3 class="feature__title">'. $row['area'] .' '. $row['block_number'] .'</h3>
<p class="feature__text">
Structure Name: '. $row['structure_name'] .'<br>
Attended: '. $row['attended'] .'<br>
More Information
<br>
<font color="Tomato">'. $row['remove_date'] .'</p>
</div></div>';
}
}
else{
echo '<br>Sorry No Results';
}
?>
There was a space in between the equals symbol and $area1 that was making it return 0 rows. I do believe that the other comments were also correct and I will be researching ways to make my code more secure as #Barmar suggested.
area = $area1
I changed area =$area1 and it started working as expected.
Related
How would I output the selected data from the database over a certain amount of pages.
For example I'd like 20 result per page and it automatically adds the extra pages needed (bit like google search pages but no search is needed as I am getting everything from the database).
Sorry for a bad explanation and also badly indented code, new to stackoverflow. I've tried putting just the php, rest of the page isn't complete or I removed the unnecessary code, feel free to improve as well.
At the moment I am just calling all the data onto one page using very simple
code
<?php
session_start();
if(isset($_POST['logout'])) {
unset($_SESSION['Username']);
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="" style="min-width: 1024px; max-width: 1920px; margin: 0 auto; min-height: 1280px; max-height: 1080px;">
<?php
if (isset ($_SESSION['Username']))
{
?>
<button onclick="location.href = 'logout.php';">Logout</button>
<?php
if (isset ($_SESSION['Username']))
{
echo "";
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "request";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM request";
$result = $conn->query($sql);
$sql = "SELECT * FROM request ORDER BY id DESC";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if (isset ($_SESSION['Username']))
{
?>
<div align="center">
<div class="requests">
<p><?php echo $row["Name"]; ?></p>
<p><?php echo $row["Number"]; ?></p>
<p><?php echo $row["Song"]; ?></p>
</div>
</div>
<?php
}else{
header("Location: index.php");
}
}
} else {
echo "0 requests";
}
}
mysqli_close($conn);
?>
Let's see an example of pagination in PHP. Before that, we need to understand what pagination is. Result pagination is quite simple.
We do a search on a certain DataBase table, and with the result of the search, we divide the number of records by a specific number to display per page.
Related: Data pagination in PHP and MVC
For example a total of 200 records, and we want to display 20 per page, we will soon have 200/20 = 10 pages. Simple, right? Well let's go to the code then.
First connect to MySQL:
<?php
$conn = mysql_connect("host","user","pass");
$db = mysql_select_db("database");
?>
Now let's create the SQL clause that should be executed:
<?php
$query = "SELECT * FROM TableName";
?>
Let's get to work ... Specify the total number of records to show per page:
<?php
$total_reg = "10"; // number of records per page
?>
If the page is not specified the variable "page" will take a value of 1, this will avoid displaying the start page 0:
<?php
$page=$_GET['page'];
if (!$page) {
$pc = "1";
} else {
$pc = $page;
}
?>
Let's determine the initial value of the limited searches:
<?php
$begin = $pc - 1;
$begin = $begin * $total_reg;
?>
Let's select the data and display the pagination:
<?php
$limit = mysql_query("$query LIMIT $begin,$total_reg");
$all = mysql_query("$query");
$tr = mysql_num_rows($all); // checks the total number of records
$tp = $tr / $total_reg; // checks the total number of pages
// let's create visualization
while ($dados = mysql_fetch_array($limit)) {
$name = $data["name"];
echo "Name: $name<br>";
}
// now let's create the "Previous and next"
$previous = $pc -1;
$next = $pc +1;
if ($pc>1) {
echo " <a href='?page=$previous'><- Previous</a> ";
}
echo "|";
if ($pc<$tp) {
echo " <a href='?page=$next'>Next -></a>";
}
?>
Ready, your pagination in PHP is created!
I'm making a page where you have to enter a text in a textbox and the click send, another page will save it.
Also, on the first page, the text that was stored previously in the database, has to load. This is the code that i've got:
<?php
$databaseid = 3;
$servername = "jog4fun.be.mysql";
$username = "jog4fun_be";
$password = "****";
$dbname = "jog4fun_be";
$gettitel1 = null;
$gettext1 = null;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Id,Titel,Tekst FROM Teksten";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
}
} else {
echo "0 results";
}
$conn->close();
$gettitel1 = strip_tags($gettitel1, '<br>');
$link1 = '<textarea id = "klein" rows="4" cols="50" name="titel3" form="usrform">' . $gettitel1 . '</textarea>';
$link2 = '<textarea id = "groot" rows="4" cols="50" name="text3" form="usrform">' . $gettext1 . '</textarea>';
echo $link1;
echo $link2;
?>
The problem is that it sends the text from textbox with name text3 as text1 with the post function. Can someone figure out what's wrong with it? I've been tying for an hour and i did not find it.
Thanks for your time and help,
Jonas
Simply here:
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
you overwrite the value of the two variables each time you iterate. So after this block of code you will keep stored the last values returned from the db.
YOu should add to your query a WHERE clause to identify the one and only record you need so you will fetch only the relevant data. Example:
$sql = "SELECT Id,Titel,Tekst FROM Teksten WHERE Id='1'";
Im trying to make an image click counter, so that when some one click on an image it updates hit column by 1.
Im having trouble with the syntax, as far as getting the row number that needs to be updated.
Later i want to use this hit column to sort the order that the images are displayed on the site.
If you feel like throwing me a bone and telling how to do that as well it would be much appreciated :)
connect.php
<?php
$servername = "*******";
$username = "********";
$password = "********";
$dbname = "********";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
?>
art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='img/".$row["name"].".jpg '
//part that I need help with
onclick='
<?php
include 'update_hits.php';
update_hit('$row');
?>'
target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
update_hits.php
<?php
require 'connect.php';
function update_hit($row){
$query = "SELECT 'hits' FROM 'art'";
if(#$query_run = mysql_query($query);){
$count = mysql_result($query_run, '$row' , 'hits');
$count_inc = $count + 1;
$query_update = "UPDATE 'art' SET 'hits' = '$count_inc'";
#$query_update_run =mysql_query($query_update);
}
}
?>
Finally got it to work
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo "<img src='".$image.".jpg'>"; // prefix full path if needed
$imagename = explode("/", $image);
$sql = "UPDATE `art` SET `hits`=`hits` +1 WHERE `name` = '".$imagename[1]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
This is only the logic, your code is not perfect it needs many validation and additional checks. I have not tested this code check for syntax errors. Its only for you to get the logic on how to do this.
modified art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='displayImg.php?image=".$row["name"]."' target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
new displayImg.php
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo 'img/'.$image.'jpg'; // prefix full path if needed
$sql = "UPDATE 'art' SET hits=hits+1 where name = ".$image;
$result = $conn->query($sql);
}
?>
I'm trying to select all data from all tables that belong to a specific database with MySQLi.
So, I am looking for something like SELECT * FROM *
I have the following (awesome) code, but it isn't working. Can someone enlighten me?
<h1>All posts</h1>
<?php
$servername = "localhost";
$username = "Masa";
$password = "passwdhere";
$dbname = "forums";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM *";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h3>' . $row["title"] . '</h3><br><br><p>' . $row["text"] . '</p><br> <h4>Answers</h4><br><p>' . $row["answer"] .'</p><br> <form method = "post"><label for = "answer">Post your answer</label><br><textarea class = "answer" id = "answer" name = "answer" requred maxlength="10000" ></textarea><br><input type = "submit" class = "submit" name = "submit" id = "submit" value = "Answer"></form><br> <hr style="width: 650px; max-width: 100%; color: #eee;"><br><br> ';//I know, don't print HTML tags :3
}
} else {
echo "No posts yet! :c";
}
$conn->close();
?>
You want to use show tables; - that being said, I'd recommend reading the MySQL documentation or a tutorial this is really basic stuff. I'm sure just searching on SO would have given you the answer too.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
im working on a project for basically my friends and i to use. Maybe to use it for other games as well. SpeedRunning! i have made and was able to POST the Data into MySQL with THIS information
<?php include_once('include/action_page.php');?>
<!DOCTYPE HTML>
<meta charset="UTF-8">
<html>
<head>
<title>Roleplayer's Tavern Home</title>
<link href="/style/style.css" rel="stylesheet" type="text/css">
<script src="/include/jquery-1.11.2.min.js"></script>
<?php include_once('/include/rpt_site_no_script.php');?>
</head>
<body onload="">
<div class="page_container" name="page_container">
<div id="page_header">
<!-- The title of the webpage -->
<div style="max-width:250px; overflow:hidden">
<span id="header_title"><img src="style/logo.png" style="width:225px; height:67px;"/></span>
</div>
</div>
<!-- Left side bar -->
<div id="page_container_left">
<h3 id="page_content_header">Submit your data!</h3>
<?php include('include/submit_data.php');?>
</div>
<div id="page_container_right"
style="overflow-y: auto; max-height: 100%">
<h3 id="page_content_header">Donations for website?</h3>
<?php
?>
</div>
<!-- Main Content -->
<div id="page_content_container_main_page">
<div class="page_content_container">
<h2 id="page_content_container_header">Leaderboard WOO WOO</h2>
<hr>
<p id="page_content_container_content">
<h2>Players That Have Beaten Mad Pack 2</h2>
<?php include('include/leaderboard.php');?>
</div>
</div>
<br>
<!-- Footer -->
<div id="page_footer">
<ol id="footer_list">
<li>Copyright © Roleplayer's Tavern 2015-2016 - All Rights Reserved</li>
<li style="font-size:12px">Your IP address <?php echo $_SERVER['REMOTE_ADDR']; ?> will be logged for security reasons.</li>
</ol>
</div>
</div>
<script type="text/javascript">
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
window.onresize = function(event) {
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
}
</script>
</body>
</html>
as this is the HTML format.
Action_page.php is the page for submitting the information
<?php
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$sql = "INSERT INTO MineCraftRecords (MineCraftName, LevelSeed, Day, Time)
VALUES ('$_POST[MinecraftName]', '$_POST[LevelSeed]', '$_POST[Day]', '$_POST[Time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
$conn->close();
?>
<meta http-equiv="Location" content="https://rptavern.org/SpeedRun/">
and im having trouble on getting the page to LOAD the information provided into the leaderboard.php as this is what i have so far.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
$query="SELECT * FROM MineCraftRecords";$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;while ($i < $num) {CODE$i++;}
$variable=mysql_result($result,$i,"fieldname");
$field1-name=mysql_result($result,$i,"MineCraftName");
$field2-name=mysql_result($result,$i,"LevelSeed");
$field3-name=mysql_result($result,$i,"Day");
$field4-name=mysql_result($result,$i,"Time");
$field5-name=mysql_result($result,$i,"id");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
?>
Im basically trying to base it off this website http://www.speedrun.com/mc but not as technical. Just to show the SpeedRunning time and have the TIME the top of the list.
Any help is awesome, as im very new to creating stuff like this. i will take the time to read everyone's comments and suggestions that you all can provide :D
I suggest cleaning up your code. Some thing that can be done is that you can separate the dB connect details into a separate file. This will optimize your code and will it make sure to change the details later on as your project grows.
If you would ever consider using PDO here is a code example that will help you out. I'm not sure if mySQLi is similar to PDO but have a look anyway. It's super easy to use and implement in as many pages as possible!
HTML/PHP (displaying data in table):
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
</head>
<body>
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
require_once("../DAL/db_functions.php");
//Run query on branch table
readQuery("M_Branch");
//If there are any details in branch table continue
if($numRecords === 0){
echo "<p>No Branches Found!</p>";
}
else{
$arrRows = NULL;
//Create table and headings
echo "<table id='mavis' border='1' width='100%'>";
echo "<tr>";
echo "<th>Branch Code</th>";
echo "<th>Branch Name</th>";
echo "<th>Manager</th>";
echo "<th>Branch Address</th>";
echo "<th>Suburb</th>";
echo "<th>State</th>";
echo "<th>Post Code</th>";
echo "<th>Phone Number</th>";
echo "<th>Fax Number</th>";
echo "<th></th>";
echo "</tr>";
while($arrRows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>".$arrRows['Branch_Code']."</td>";
echo "<td>".$arrRows['Branch_name']."</td>";
echo "<td>".$arrRows['Manager']."</td>";
echo "<td>".$arrRows['Branch_Address']."</td>";
echo "<td>".$arrRows['Suburb']."</td>";
echo "<td>".$arrRows['State']."</td>";
echo "<td>".$arrRows['Post_code']."</td>";
echo "<td>".$arrRows['Phone']."</td>";
echo "<td>".$arrRows['Fax']."</td>";
//Cannot delete already created records - Foreign key constraint fails
//If phpMyadmin were to delete one then other tables will incur problems
echo "<td><a href='edit_branch.php?ID=$arrRows[Branch_Code]'>Edit</a>";
echo "<br /><a href='../BLL/delete_confirm.php?TYPE=Branch&ID=$arrRows[Branch_Code]' onClick='return checkDelete()'>Delete</a></td></tr>";
}
echo "</table>";
echo "<form action='../DAL/add_branch.php' method='post'>";
echo "<input type='submit' value='Add a New Branch' />";
echo "</form>";
echo "<p></P><P>$numRecords Records Returned</P>";
}
?>
</body>
Here is my connect and readQuery function located in ../Db_functions.php
I have created functions that are reusable and can be used with multiple DB tables.
//Database connection Variables
$localhost = "localhost";
$user = "root";
$password = "root";
$db = "Mavis";
$dsn = "mysql:host=$localhost;dbname=$db";
//Declare Global Variables
$dbConnection = NULL;
$stmt = NULL;
$numRecords = NULL;
//This connect database function can be used to connect anywhere
function connect(){
//These are variables from the other file (dblibary) - global allows access to these variables
global $user, $password, $dsn, $dbConnection; //Required to access the global variables.
try{
$dbConnection = new PDO($dsn, $user, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error){
//display error message if connection doesnt work
echo "The following error occured: " . $error->getMessage();
}
}
Read Query:
function readQuery($table){
global $numRecords, $dbConnection, $stmt;
connect();
$sqlStr = "SELECT * FROM " . $table.";";
try{
$stmt = $dbConnection->query($sqlStr);
if($stmt === false){
die("Error executing the qquery: $sqlStr");
}
}
catch(PDOException $error){
echo "An Error occured: " . $error->getMessage();
}
$numRecords = $stmt->rowCount();
//Close the DB connection
$dbConnection = NULL;
}