Working on a small project with some simple sql query injection in my php file. I have created a functions.php file with a function called function displayimage(). I include my function file in my index file and use the function like so
index.php
<div class="col-lg-2">
<?php displayimage(); ?>
</div>
Functions.php
function displayimage()
{
$dbCon = mysqli_connect("localhost", "root", "root", "testdb");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql= "SELECT * FROM `images` ORDER BY `images`.`id` DESC ";
$query=mysqli_query($dbCon, $sql);
if ($row = mysqli_fetch_array($query))
{
echo '<img class="img-responsive" style="margin-top: 10px;" src="data:image;base64,'.$row[2].' "> ';
}
mysqli_close($dbCon);
}
?>
So it works fine but.. I tried to clean my code by putting the database connection in a seperate file, and including it like include('connection.php');. Unfortunately my code doesn't work anymore, and the content won't show up at my index file. My PHPStorm says that $dbCon is a undefinable variable now. What am I doing wrong here?
new functions.php
function displayimage()
{
include('connection.php');
$sql= "SELECT * FROM `images` ORDER BY `images`.`id` DESC ";
$query=mysqli_query($dbCon, $sql);
if ($row = mysqli_fetch_array($query))
{
echo '<img class="img-responsive" style="margin-top: 10px;" src="data:image;base64,'.$row[2].' "> ';
}
mysqli_close($dbCon);
}
?>
connection.php
$dbCon = mysqli_connect("localhost", "root", "root", "testdb");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
You should include connections.php on the top on your page if you want to make a connection to a database. However if you're using mysqli I would recommend using the object orientated syntax over the procedural. That way you don't have to parse the $connection variable each time you query.
require_once 'connection.php';
function displayimage(){
global $dbCon;
$sql= "SELECT * FROM `images` ORDER BY `images`.`id` DESC ";
if($qry= mysqli_query($dbCon, $sql) != false){
// query ran successfully, here you should actually continue the code..
while($row = mysqli_fetch_array($query)){
echo '<img class="img-responsive" style="margin-top: 10px;" src="data:image;base64,'.$row[2].' "> ';
}
} else {
echo 'failed to retrieve images from the database.';
}
}
Also, you don't have to close the connection every time when you're done querying. Its done automatically at the end of the script and without it it can continue to use the already opened connection.
However it is bad practice to use global variables in functions, just make sure you never overwrite the $dbCon variable, it might happen when using code from somebody else.
Related
for the past few i have been trying to get the ID of the event a user registers to inside the URL in order to show all details in that event.
Ive tried Get data from MySQL database by specific id in url
But it doesnt seem to work for what i am trying to do.
Or i am doing it wrong, i got more progress with this code
<?php
if(isset($_SESSION['user_id'])){
$userid = $_SESSION['user_id'];
$QUERY3 = mysqli_query($DB, "SELECT * FROM `registration` WHERE `user_id`='$userid'");
$GETEVENTZ = mysqli_fetch_array($QUERY3);
}
?>
<?php
$eventid = $GETEVENTZ['event_id'];
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>'
?>
Just to try and get the ID in but im getting a normal page
with the url being
leaderboard.php?eventid=
and no ID after, no errors are popping up, page and everything loads, just doesnt add ID. cant seem to find the issue
Since your are using: $GETEVENTZ = mysqli_fetch_array($QUERY3);
Your code is expecting an array return. So you cannot just simply use:
$eventid = $GETEVENTZ['event_id'];
A quick fix can be $eventid = $GETEVENTZ[0]['event_id'] if you are expecting a single row return from your query.
But the proper way to handle this is to use mysqli_fetch_row() instead.
You can also dump the result set first to debug what your query is returning.
The session super global is not the one to use. Use $_GET to get information from the URL.
<?php
if(isset($GET['user_id'])){
$userid = $GET['user_id'];
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query3 = "SELECT * FROM `registration` WHERE `user_id`=?";
if($stmt = $mysqli->prepare($query3)) {
$stmt->bind_param("s", $userid);
$stmt->execut();
$result = $stmt->get_result();
}
}
?>
<?php
// this section does not demonstrate getting the value from $result
// I will update answer later, must research mysqli more.
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>'
?>
Disclaimer: I don't use mysqli, so my answer is a best guess on that portion. Be sure to research how to properly use prepared statements at http://php.net/manual/en/mysqli.prepare.php
Try this, Hopefully it will work.
<?php
$DB = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if ($DB->connect_errno) {
printf("Connect failed: %s\n", $DB->connect_error);
exit();
}
if(isset($_SESSION['user_id'])) {
$userid = $_SESSION['user_id'];
$QUERY3 = "SELECT * FROM registration WHERE user_id='$userid'";
$result = $DB->query($QUERY3);
$GETEVENTZ = $result->fetch_array(MYSQLI_ASSOC);
$eventid = $GETEVENTZ['event_id'];
printf ("%s", $eventid);
}
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>';
?>
Answer -
Session id was labeled (userid) instead of (user_id)
then after i stated if user session has user ID then print the event ID and then show page, which then it redirects me to the correct page with ID of event
<?php
if(isset($_SESSION['user_id'])){
$GETUSRID = $_SESSION['user_id'];
$GETRANKD = mysqli_query($DB, "SELECT * FROM `registrations` WHERE `user_id`='$GETUSRID'");
$GETRD = mysqli_fetch_assoc($GETRANKD);
$eventid = $GETRD['event_id'];
printf ("%s", $eventid);
}
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>';
i am a newbie in php programming and i cant figure out where i have gone wrong as my php code wont execute.
As the title says i am trying to create check boxes in my site however the values will come from the mysql database.
I have a table named “campus” in MySQL database and it has 2 coloumns called id and room.
database
[![Database][1]][1]
http://i.imgur.com/uLP6niJ.png
current output
[![Current Output][2]][2]
http://i.imgur.com/cSOYPme.png
below is my code:
<?PHP
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$s = '';
$j = 0;
if ($q = $connect->query("SELECT * FROM `campus`")) {
while ($line = $q->fetch_assoc()) {
$s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
}
}
echo $s;
?>
</form>
</body>
</html>
You're not closing the while loop properly. Close the while loop as follow.
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line['room']?>" />
<?php
}
?>
Welcome to PHP!
An error is that you're missing the semicolon that's needed after any php function (such as echo)
<?php echo $line['room']; ?>
And there's the missing PHP tags around the closing }
A third error is that you're not telling mysqli which connection to run the query on it should have:
mysqli_query($dbCon, $sql);
Apart from that it looks good, personally I prefer to use a PDO connection but mysqli is still good, but there are a few formatting tricks that can help prevent problems.
For example it's always a good idea to use back-ticks (`)
So:
$sql = "SELECT `room` FROM `campus`";
However, for this it might be best to use the * query. Which selects everything from the column so:
$sql = "SELECT * FROM `campus`";
The reason is how you're getting the data, you're telling PHP to create an array using the results.. but you've only given it one piece of data for each row. So if you give it all of the data it just makes it a little easier to use.
Here's the full code:
<?php $dbCon = mysqli_connect("localhost", "root", "root", "my computer");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$sql = "SELECT * FROM `campus`";
$result = mysqli_query($dbCon, $sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { ?>
<input type="checkbox" name="car" value="<?php echo $line['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Also, if you're interested, here's how it'd be done in PDO:
<?php
try{
$con = new \PDO("mysql:host=" . 'localhost' . ";dbname=" . 'My Computer', 'root', 'root');
}catch(PDOException $e){
echo "Connection Failed";
die();
} ?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$result = $con->prepare("SELECT * FROM `campus`")
$result->execute();
while ($row = $result->fetch()) { ?>
<input type="checkbox" name="car" value="<?php echo $row['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Still not working? Feel free to comment and I'll see what's up :)
Thanks,
P110
Try with this
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
$campusArray = mysqli_fetch_array($result, MYSQLI_ASSOC);
foreach ($campusArray as $campus): ?>
<input type="checkbox" name="car" value="<?php echo $campus['room'];?>" />
<?php endforeach; ?>
I hope with this you can solve your problem.
alternative syntax is excellent for improving legibility (for both PHP
and HTML!) in situations where you have a mix of them.
http://ca3.php.net/manual/en/control-structures.alternative-syntax.php
I am trying to produce an outcome if both rows in two different tables match, but I am having a hard time trying to make it work. Can someone please tell me if I am missing something.. Thank you in advance
**Note: my connections are in an included file and both tables are in the same database
<html>
<p>Pending Documents</p>
<?php
$sql ="SELECT * FROM `forms`";
if ($_SESSION['user_name'] == $row["username"]){ ?>
<p>SUTA Document</p>
<? }else { ?>
<p>No Pending Documents</p>
<? } ?>
</html>
You should solve it with mysqli. Here is a working snippet:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . mysqli->connect_error;
}
if ($result = $mysqli->query("SELECT * FROM `forms`")) {
while ($obj = $result->fetch_object()) {
if ($_SESSION['user_name'] == $obj->username){ ?>
<p>SUTA Document</p>
<? }else { ?>
<p>No Pending Documents</p>
<? }
}
$result->close();
}
$mysqli->close();
?>
I have got a code that should get all of the user's Favourites from favourites and then it should use that information to get the info from menus to display them as pictures.
All it should do is display the user's Favourites but at the moment it will only display one picture when there are many in their Favourites.
<?php
$con=mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id=$_SESSION['user']['id'];
$result = mysqli_query($con,"SELECT * FROM favourites WHERE user='$id'");
while($row = mysqli_fetch_array($result)) {
$code=$row['gamecode'];
$con=mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM menus WHERE code='$code'");
while($row = mysqli_fetch_array($result)) {
?>
<a href="<?php echo $row['link']; ?>">
<img src="<?php echo $row['picture']; ?>" alt="<?php echo $row['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
mysqli_close($con);
}
mysqli_close($con);
?>
You're killing your query by reconnecting to the DB inside your loop
$con = mysqli_connect(...) // connection #1
$result = mysqli_query(...);
while($row = mysqli_fetch($result)) {
$con = mysqli_connect(...); // connection #2
When you connect again, you kill the original connection, which kills your query.
Unless you need to connect twice with different credentials, there is NO need for a second connection. One single connection can handle multiple queries.
Incidentally, if you'd used a different connection handle variable, e.g.
$con = mysqli_connect(...);
$othercon = mysqli_connect(...);
you wouldn't have had the problem. You CAN have multiple connections, but not using the same single variable.
You have two MySQL connections with the same variable names of $con as well as $result & $row. So I just change the variable names on the inside loop so they don’t conflict & all should work; $con_inside, $result_inside & $row_inside.
I also added or die(mysqli_error()); to your mysqli_query lines so errors can be returned if your query dies.
<?php
$con = mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_SESSION['user']['id'];
$result = mysqli_query($con, "SELECT * FROM favourites WHERE user='$id'") or die(mysqli_error());
while ($row = mysqli_fetch_array($result)) {
$code = $row['gamecode'];
$con_inside = mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_inside = mysqli_query($con_inside, "SELECT * FROM menus WHERE code='$code'") or die(mysqli_error());
while($row_inside = mysqli_fetch_array($result_inside)) {
?>
<a href="<?php echo $row_inside['link']; ?>">
<img src="<?php echo $row_inside['picture']; ?>" alt="<?php echo $row_inside['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
mysqli_close($con_inside);
}
mysqli_close($con);
Also, here is a slightly reworked version of your code that should work better. I removed the inside DB connection from the loop & set it at the top of the script. The connection does not have to be reset on each loop. Also, I added lines using mysqli_stmt_bind_param which is a preferred way of using mysqli_* queries instead of setting strings. Also using mysqli_free_result to free up query memory on each loop. These are small things but they add up to better code.
<?php
// Main DB connection.
$con = mysqli_connect("localhost","UN","PW","DB") or die(mysqli_connect_error());
// Inside DB connection.
$con_inside = mysqli_connect("localhost","UN","PW","DB") or die(mysqli_connect_error());
// Set the $id variable.
$id = $_SESSION['user']['id'];
// Set the query string.
$query = "SELECT * FROM favourites WHERE user='$id'";
// Bind the values to the query.
mysqli_stmt_bind_param($query, 's', $id);
// Get the result.
$result = mysqli_query($con, $query) or die(mysqli_error());
// Roll through the results.
while ($row = mysqli_fetch_array($result)) {
// Set the $code variable.
$code = $row['gamecode'];
// Set the query string.
$query_inside = "SELECT * FROM menus WHERE code='$code'";
// Bind the values to the query.
mysqli_stmt_bind_param($query_inside, 's', $code);
// Get the result.
$result_inside = mysqli_query($con_inside, $query_inside) or die(mysqli_error());
// Roll through the results.
while($row_inside = mysqli_fetch_array($result_inside)) {
?>
<a href="<?php echo $row_inside['link']; ?>">
<img src="<?php echo $row_inside['picture']; ?>" alt="<?php echo $row_inside['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
// Free the result set.
mysqli_free_result($result_inside);
// Close the connection.
mysqli_close($con_inside);
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
See if it works using different result variables and only one DB connection.
<?php
$con=mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_SESSION['user']['id'];
$result1 = mysqli_query($con,"SELECT * FROM favourites WHERE user='$id'");
while($row = mysqli_fetch_array($result1)) {
$result2 = mysqli_query($con,"SELECT * FROM menus WHERE code='".$row['gamecode']."");
while($row2 = mysqli_fetch_array($result2)) { ?>
<a href="<?php echo $row2['link']; ?>">
<img src="<?php echo $row2['picture']; ?>" alt="<?php echo $row2['game']; ?>" height="120" width="150" class="fade"></a>
<?php }
}
mysqli_close($con);
?>
Ok, So I have a external php script that get data from a DB and displays it in a table. I want to run it in a specific div in my html so the data gets echoed out in the right place?
Any ideas how to do that?
Html div
<div id="statsContent">
<?php include('updatestats.php'); ?>
</div>
Heres the PHP code.
<?php
//Start session
session_start();
//Make sure user is logged in
require_once('auth.php');
//Include database connection details
require_once('config.php');
//Connect to DB
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Create Querys
$query = "SELECT * FROM stats WHERE member_id='" . $_SESSION['SESS_MEMBER_ID'] . "' ";
$result = mysql_query($query);
//Gather the whole row into an array
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$money = $row['money'];
$bank_money = $row['bank_money'];
$ap = $row['ap'];
$exp = $row['exp'];
}
//Now create a table to display the data to the user
echo "<table>
<tr>
<td>Money $$money</td>
<td>Action Points $ap</td>
<td>Experience $exp</td>
</tr>";
?>
you can include PHP script in any tag by calling
include("path_to/myscript.php") or require("path_to/myscript.php")
<div>
<?php include("path_to/myscript.php"); ?>
</div>
<div><?php *whatever you want to do inside the div*?></div>
just include it inside your div by using:
<?php include('filename.php'); ?>