Grab data from a query - php

I'm trying to learn PHP, and to do so I'm attempting to create a URL shortener. Right now you can currently input a link and it enters it into the database. It doesn't randomize the string, but I'm going to do that after. (I changed them myself to avoid running into problems).
Here is my table currently(My table is called 'urls'):
Then when you go to (for me localhost) /somepath it automatically redirects to /process.php?id=somepath
In process.php it checks if the specified path (somepath) exists in the database, then gets its original value. The problem I'm having is getting the original value. Again, I am new to PHP, and I'm having trouble understanding how querying works.
$query = "SELECT original FROM urls WHERE new = '$new'";
$result = $conn->query($query);
How do I grab information from $result? Or am I supposed to get it from $query after $result because that just basically runs it?
Please explain why you use what, I'm not understanding this.
Thanks, sorry if this is a really stupid question.

In this code, I used the object oriented approach for a prepared statement or if you are still into procedural style, you can still use that.
Check this link: http://php.net/manual/en/mysqli.prepare.php
So basically, what happens in this code is that the query is being prepared then you bind the parameter to be used (this style is one way to avoid SQL injections because inputs are automatically escaped). The result will be first stored in the variable $original then I counted how many rows the query returned. If it is more than 1, it means there is a match, then if 0, no match.
If there is a match, it will echo the value of the variable $original.
<?php
$stmt = $conn -> prepare("SELECT original FROM urls WHERE new = ?");
$stmt -> bind_param('s',$new);
$stmt -> execute();
$stmt -> bind_result($original);
$stmt -> fetch();
$stmt -> store_result();
$res = $stmt -> num_rows();
$stmt -> close();
if($res > 0){
echo $original;
}
else{
//not found
}
?>

Use fetch_assoc() to grab data from your table in MySQLi Object-oriented.
Try this:
$query = "SELECT original FROM urls WHERE new = '$new'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
You can also put the result in an HTML table:
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

$query = "SELECT original FROM urls WHERE new = '$new'";
$result = $conn->query($query);
$rows = mysql_fetch_array($result);
foreach($rows as $row){
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
You can use either mysql_fetch_array or mysql_fetch_assoc for grab results

Related

Creating An Array from MYSQLI query

I am updating all my code to Mysqli, before I did I had this code and it worked:
while($row = mysql_fetch_assoc($WildHorses)){
$InWild[] = $row['id'];
}
$RandomWild = array_rand($InWild);
$RandomHorse = $InWild[$RandomWild];
This is my SELECT statement:
$sql = "SELECT Horse.id, Horse.Name, Horse.Age, Horse.Image_name, Horse.Owner, Horse.Barn, Images.Image_path, Images.Image_name FROM Horse, Images WHERE Horse.Owner = '$colname_WildHorseList' AND Images.Image_name = Horse.Image_name";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " Name: " . $row["Name"]. " ImageName: " . $row["Image_name"]. "<br>";
}
} else {
echo "0 results";
}
The SELECT statement ends up echoing all of the correct information, but I want to make an array of only the Id's so that I can pick one at random each time a button is clicked.
I have tried multiple different copies and pastes of code to try and get what I want, but nothing seems to come out right.
Can someone point me in the right direction or explain what I'm doing wrong?
In your while loop you can simply do this :-
$i=0;
$animals=array();
$animals[$i]=$row["id"]; //puts id in array
And then you can create a random number by "rand()" between the length of 0-$i
and can get the job done.

How to retrieve the name of a link?

I have a database and I generated a code that creates links depending on the name of the person in the database and I want the names to be
"sent" in the next page ( link's page). So I used the method "get" to do that but it does not work and I don't know why.
$sql = "SELECT * FROM table_personne; ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ("<a href=\"traitement.php?firsname=".$row["firsname"]."%"."&lastname=".$row["lastname"]."%".">".$row["firsname"]. " ".$row["lastname"]);
echo "<br>";
}
} else {
echo " 0 results";
}
The URL that is created is: traitement.php?prenom=paul%&nom=vincent%>paul%20vincent
Problems: The URL does not match the name of the person displayed and the lastname is "vincent%>paul" meaning lastname=$GET["lastname"]= "firstname%lastname<" and there is no $GET["firstname"].
Thanks a lot.
What about this :
echo (''.$row["firstname"]. " ".$row["lastname"]).'';
Maybe You have to change this :
$row["firsname"]
to
$row["firstname"]

Use POST method to display data from database PHP

I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

no results shown when I enter the if statement

This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.

Categories