How do i display content from a MySQL DB in PHP - php

OK, the title may be misleading, I'm a complete novice in MySQL queries via PHP
What im actually trying to do is display a specific title of a row in a link.. for instance:
<?php echo "Link Name"; ?>
url being the row which holds the name of the link eg, link-one. So the finished link would output (if you were to view source):
Link name
My question is how do i select a certain entry in the url row? not just the next/previous/random entry. This may be easy but i cant find an answer. Is this possible?

Will this do the trick?
SELECT url,fn FROM $dbtable WHERE url LIKE '%link-one' ORDER BY order ASC

For this you would do something like:
$sql = "SELECT * FROM table WHERE id='$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo ''.$row["name"].'';
Though php isn't as useful if you don't have a db back end I recommend reading through W3School's sql tutorials, they are quiet good (and free) http://www.w3schools.com/Sql/default.asp

Related

Can't fetch a single field from database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I try to do it it fetches the entire column, not just one field.
$connection = mysqli_query($db, "SELECT * FROM users");
<?php
while($row = mysqli_fetch_array($connection)) {
?>
<p>Your balance is: <?php echo $row['balance']; ?></p>
<?php
}
?>
That was outputting
Your balance is: 5
Your balance is: 0
Your balance is:
So I tried
$query_for_selecting = mysqli_query($db, "SELECT balance FROM users");
<?php if (mysqli_num_rows($query_for_selecting) > 0) { ?>
<?php while($row = mysqli_fetch_assoc($query_for_selecting)) { ?>
<p>Your balance is <?php $row['balance']; ?></p>
<?php } ?>
<?php } ?>
And that wasn't outputting anything so eventually, I tried using a WHERE clause and a limit of 1
$query_for_selecting = mysqli_query($db, "SELECT * FROM users WHERE balance = '3' DESC LIMIT 1");
<?php if (mysqli_num_rows($query_for_selecting) > 0) { ?>
<?php while($row = mysqli_fetch_assoc($query_for_selecting)) { ?>
<p>Your balance is <?php $row['balance']; ?></p>
<?php } ?>
<?php } ?>
All I got was a white screen
I think a basic little tutorial might be in order here.
First off: SELECT * FROM users means: "give me everything in the users table". You will get the full table, every row and every column.
while($row = mysqli_fetch_array($connection)) will loop through every row your query returns. It will call mysqli_fetch_array() and put the result in $row until there are no more rows in your query's result.
If you only want to output a single row of data, you have three options:
Add a WHERE condition so that your query will only fetch a specific row
Add a LIMIT clause so that your query will only fetch a single row
Call mysqli_fetch_array() only once instead of in a while loop
From the comments in the discussion thread, it looks like you want to retrieve only the balance for the currently logged in user, and you have a session variable somewhere that tells you who that user is. That means you'll want to use a WHERE condition so that your query will only fetch the row for that specific user.
You haven't told us what that session variables is called or what the name is of the column in the users table that you can compare that session variable with, so I'll assume that your users table has an id column and your session variable is called user_id and should match the id value from your users table.
So let's say the user with id 123 is currently logged in. You'll want to end up with the query SELECT balance FROM users WHERE id = 123.
The quick solution is to change your code to:
$connection = mysqli_query($db, "SELECT balance FROM users WHERE id = " . $_SESSION['user_id']);.
This is bad code. We'll make it better, but try this first and see if it gets you the result you actually want. If it doesn't, let me know.
The reason this is bad code is because adding variables to a query string like this dramatically increases the risk of SQL injections. If there's any possibility at all that the value of the variable comes from user input, then at some point a user will figure that out and make sure it contains something that will break your application.
Best case scenario: the page simply won't render for that one user.
Bad case scenario: the user will be able to read out your entire database and will sell sensitive user data to the highest bidder.
Worst case scenario: the user will be able to inject some of their own Javascript code into your database in a column you're not sanitizing before rendering, letting them capture and intercept passwords and/or financial information your users are entering on your site and they will then use that information to make life miserable for all of your users.
So you don't want to just drop $_SESSION['user_id'] into your query like that. Instead, you'll want to use a prepared statement and let the database handle the problem of dropping the variable into the query.
First, you'll need to prepare your query:
$statement = mysqli_prepare($db, "SELECT balance FROM users WHERE id = ?");
The ? symbol is a placeholder where you can bind a parameter. Let's do that:
$statement->bind_param("i", $_SESSION['user_id']);
The "i" tells MySQL that you're binding an integer value. If you're not matching against a user id but a username, for example, you'll want to instead use "s" to tell MySQL you're binding a string value.
Now you can execute the query and get the result. Putting it all together:
$statement = mysqli_prepare($db, "SELECT balance FROM users WHERE id = ?");
$statement->bind_param("i", $_SESSION['user_id']);
$statement->execute();
$connection = $statement->get_result();
Let us know if that works. Some tweaking might be required.
I have a feeling as to what's going on. You're fetching the entire database without either using a LIMIT of 1 and/or use a WHERE clause, given that you have unique ID's somewhere for columns. I am sure that you have more than the one record in your database table.
I was going to post this in a comment but decided not to. Stack doesn't really want us to do that, (edit) and at this point, it is way too long for a comment.
#ADyson "I initially wanted to display the balance of the user that's logged in, but that didn't work out." – markthedark
About that. It seems that what you are looking for is to get the balance for a user/record in particular. For that, you definitely need to use a WHERE clause.
If your query failed, enable error reporting and checking for errors on the query.
References:
https://www.php.net/manual/en/function.error-reporting.php
https://www.php.net/manual/en/mysqli.error.php
Plus, the $i = 0; and $i++; may not be helping. It's hard to say what that is supposed to do. I know the syntax, I just don't know why you're wanting to increase it.
Side note: I would avoid in using $connection as a query variable assignment. It could be confusing. Try to use something clear like $query_for_selecting.

How to output the MySQL EXPLAIN data in php?

I wonder if there is a way to output the EXPLAIN data from an MYSQL statement to PHP.
For studying I need to write a small application in PHP that outputs data via a SELECT query from a MYSQL DB. I have to output the EXPLAIN data, like searched rows etc., from this query as well. If I just set EXPLAIN in front of the SELECT, I get an Error.
Unfortunately I couldn't find a satisfying answer on the internet.
Due to I'm new to PHP, I would appreciate if someone can give me an example or smth like this.
Thank you guys!
You should be able to grab it using standard array tools. By using $result->fetch_array(MYSQLI_NUM); we can just grab the first return without a column name
$sql = 'EXPLAIN SELECT * FROM table WHERE condition = "condition"';
$result = $mysqli->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[0];

MySQL database manipulation with PHP

Spent the last few days researching this, but I think I'm just not getting it... I can usually do what I need to with PHP but am new to MySQL
I set up a MySQL database to hold some photos. The photo's are in separate galleries (gallery is denoted by a gallery field). The photo's are also indexed by an id number.
When displaying the photos (it all works perfectly up to now...), I would like to be able to jump to the next or previous photo in the gallery, but can't just us the next or previous id, as it could be from a different group (found that out the hard way ;)
from my research, I feel like I need to use this:
$sql = "SELECT id FROM gphoto WHERE gallery='$g' ORDER BY id DESC";
$query = mysqli_query($db_conx, $sql);
But $query doesn't seem to give me what I expect. It feels like $query it should contain an array if all id's which contain gphoto, and I should be able to just find my current id number, then jump one up or down, but when I try to read $query I get:
Cannot use object of type mysqli_result as array
I'm obviously misunderstanding something
Some people have suggested:
$result = mysqli_fetch_assoc($query);
I had tried this after reading the online manual extensively, but for some reason it only lists one item... in this case the last record.
If I run it as ASC, it lists the first. Should it be listing all records like I expect, or is it a different command?
C)
+1 for Fabio's response.
A good advice is to use PDO interface for accessing databases in PHP. It's a meaningful interface to construct, execute and fetch the results of your queries without the knowledge of the used db driver.
http://php.net/manual/en/book.pdo.php
You need to fetch data from database after executing your query to handle mysqli object you have just created
$query = mysqli_query($db_conx, $sql);
$result = mysqli_fetch_assoc($query);
Now you have the array you were looking for in your variable $result
if ($result = mysqli_query($db_conx, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
//mysqli_fetch_assoc fetches data by row
}
}
You are only getting 1 row, thats how mysqli_fetch_assoc works. If you want the entire result to be an array of the rows, use mysqli_fetch_all
I would recommend using PDO however like #ceadreak suggested.

URL rewriting and url parameter

I've been building my website from the very beginning until today with no framework or WYSIWYG software. I now realize that the way I made it could have been a lot simplier.
I'm a noob in php and mysql and wish to understand how it works. That's why I decided to make a website about a particular theme. That's the best practice to learn these 2 languages...
So,
My website goes about video content with daily updates.
I use to make per video a unique webpage... Now I've more than 300 pages of video content and I want to bring all this content into my database and put it all in one template webpage.
When I want to apply a change, I have to open all those webpages and make on each page the needed changes. Fortunatelly, the search en replace box helps me.
I just wanted to do something on the website that could make my routine and work a lot faster and easier.
I'd like to do some url rewriting with mysql requests.
I'm working on a piece of code, but I can't find what goes wrong with that.
Dreamweaver tells me that there's no error on the synthax, but when I preview it (WAMP) , it keeps showing me an error until a get rid of the 'p' paramater. Hereunder, I join you the code i'm using.
<?php
include "connect.php";
$id = $_GET["id"];
$sql = "SELECT * FROM videos WHERE id=$id LIMIT 1"; //mysql tells me there's a error near LIMIT 1
$req = mysql_query($sql) or die( mysql_error()." ERROR");
$data = mysql_fetch_assoc($req);
if($data["url"]!=$_GET["url"])
{
header("location:/video/atest.php/".$data["id"]."-".$data["url"]); //if the URL is altered, it will be immediatelly fixed thanks to this function
}
?>
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'LIMIT 1' at line 1 ERROR
Thanks to that I will be able to insert on my database every piece of content for each unique video > title, description, ... without the need to make a thousand of changes and upload new webpages.
the URL parameters are also on my database and the php scripts makes the call to the database to retrieve the URL and make this look like a unique webpage.
Oh and sorry for my English...
Thanks a lot.
Try
$id = mysql_real_escape_string($_GET["id"]);
$sql = "SELECT * FROM videos WHERE id=$id LIMIT 1";
try echo $_GET["id"]; before sql and check if you are getting any value. And also learn "PDO" it is better than using direct sql statements or as Joyce said use escape_string.
Change your line:
$sql = "SELECT * FROM videos WHERE id=$id LIMIT 1";
TO THIS:
$sql = "SELECT * FROM videos WHERE id='".$id."' LIMIT 1";
Your SELECT is selecting the string '$id' rather than the php variable $id.

Pagination updating numbers

I am wondering if there is a possibility.
I have a pagination script that grabs the content from a mysql database with php and using jquery to handle it all.
I want to add a filter to the pagination which will get rid of some content based on the users selection.
When the filter is set I would like the pagination numbers to update to compensate for the items that have been removed.
My biggest concern is that I'm getting the amount of pages to display directly from the database which would make it impossible to update the pagination numbers when filtered:
<?php
include('config.php');
$per_page = 3;
//Calculating no of pages
$sql = "select * from explore";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
Does anyone know if it is still possible to update these numbers when filtered.
Im mostly using this tutorial in case your wondering:
Here
Just to expand on what Byron said, here is how you do this (based on the code from your link):
Right now in the pagination.php there is a line that looks like this
$sql = "select * from messages";
and in pageination_data.php like this:
$sql = "select * from messages order by msg_id limit $start,$per_page";
Lets say you want a filter that only shows today's messages.
then you would need the following two lines:
$sql = "select * from messages where messages.date = curdate() ";
$sql = "select * from messages where messages.date = curdate() order by msg_id limit $start,$per_page";
of course I expect you will generate the sql statements dynamically in some way. What this allows is the sql server to do the filtering, all the application code stays as you have it.
Note: Remember if you are making dynamic sql to not leave yourself open to sql injection attacks. There are a number of other questions that address sql injection.
The solution is to do the filtration sever side. IE when you apply a filter you send the data to the server and the sql is updated to include/exclude whatever your filter says.

Categories