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);
?>
Related
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 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
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.
here is what i have try so far
<?php
//Convert the email to variable
$Tnumber2 = "{$_SESSION['Tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM $Tname WHERE Tnumber2='".$Tnumber2."'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
and here is the codes i use to echo out the variables from my mysql database
<?php echo $rows['Tnumber2']; ?>
<?php echo $rows['Idate']; ?>
<?php echo $rows['Iaddress']; ?>
thanks any help will be appricated.
try
$sql="SELECT * FROM `$Tname` WHERE Tnumber2='".$Tnumber2."'";
$result=mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $rows['Tnumber2'];
echo $rows['Idate'];
echo $rows['Iaddress'];
}
You should change the line
$result=mysql_query($sql);
to
$result=mysql_query($db,$sql)
But also, you haven't set the variable $Tname, or started a session with session_start();. Plus, there are a bunch of security holes.
When moving data from on table to another I get Error in query: Duplicate entry '0' for key 'PRIMARY'
I dont care to copy the primary key I would like each table to have its own primary key- this table will just hold data to be processed,checked and released by person them moved to a final table that will contain all processed data.
<basefont face="Arial">
<title>QA-1160 Search</title>
</head>
<body>
<?php
// include the page Header
include('header.php');
?>
<?php
//retrieve session data
echo $_SESSION['mnumber'];
echo "<P>";
$mnumber=$_SESSION['mnumber'];
$amnumber=$mnumber;
$mnumber=" '".$mnumber."' ";
// set database server access variables:
$host = "localhost";
$user = "test";
$pass = "test";
$db = "test";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database :)!");
// create query
$query = "insert into testingqa1160 (material, test, sample, frequency, stp, rtr, notes, usl, lsl) SELECT material, test, sample, frequency, stp, rtr, notes, usl, lsl FROM qa1160 WHERE material=";
$query=$query.$mnumber;
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// mysql_free_result($result);
// close connection
mysql_close($connection);
// clear session
session_unset();
session_destroy();
// load test data
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database :)!");
// create query
$query = "SELECT * FROM testingqa1160";
// $query=$query.$mnumber;
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<center><table cellpadding=5 border=1>";
echo "<tr>";
echo "<center>";
echo "<td>"."ID"."</td>";
echo "<td>"."Material"."</td>";
echo "<td>"."Test"."</td>";
echo "<td>"."Sample"."</td>";
echo "<td>"."Frequency"."</td>";
echo "<td>"."STP"."</td>";
echo "<td>"."Release"."</td>";
echo "<td>"."Notes"."</td>";
echo "<td>"."LSL"."</td>";
echo "<td>"."USL"."</td>";
echo "</center></tr>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "<td>".$row[4]."</td>";
echo "<td>".$row[5]."</td>";
echo "<td>".$row[6]."</td>";
echo "<td>".$row[7]."</td>";
echo "<td>".$row[9]."</td>";
echo "<td>".$row[8]."</td>";
echo "</tr>";
}
echo "</table></center>";
echo "</center>";
}
else {
// no
// print status message
echo "<center><FONT SIZE=18>";
echo $_GET["mnumber"];
echo " Materail is not found! </font>";
echo "</center>";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
<td>Testing</td>
<?php
// include the page footer
include('footer.php');
?>
</body>
</html>
1.- Don't use mysql_* functions, they are deprecated, use mysqli or PDO
2.- Your table testingqa1160 need to have the auto-increment attribute to the id column