PHP Displaying data from MySQL database - php

I wanted to display a page content with PHP and MySQL. But i don't know how to select and display data from PHP.
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
But i don't know how to display data. I want to get the string value from content in sql table row where name = $name and display it.
If you can, please help me

You may try and include this in your code:
$name = mysqli_real_escape_string($_GET['title']);
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
echo $row['content'];
}
mysqli_free_result($result);
Here I have assumed $link as the handle to connect to the database.
N.B.: You may consider passing the $_GET values through mysqli_real_escape_string() to avoid sql injections which may prove fatal to the database and its tables. You also need to consider the usage of mysqli_* functions because mysql_* functions are deprecated and will be discontinued.

You have error in your sql, change
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
to
$query = "SELECT * FROM pages WHERE name = '".$name."'"; // as name is char it should be enclosed in quotes
$result = mysql_query($query); // using quotes inside this will just display it without executing the query
You can fetch the results by this (if the result is only single record):
$row=mysql_fetch_array($result); // fetch the result as an array with subscript as the field name
echo $row['content']; // echo the value of the field content
If the query result contains multiple records then you have to do this inside a while loop like this:
while($row=mysql_fetch_array($result)) // fetch the result as an array with subscript as the field name
{
echo $row['content']; // echo the value of the field content
}

you have to do like this
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = '".$name."'";
$result = mysql_query($query);
//get values returned from query
$row=mysql_fetch_array($result);
//display required content
echo $row['content'];
Also mysql_* function are deprecated.You have to stop using this. Start using PDO or prepared statements or mysqli_* function

First of all the mysql_ is deprecated, use mysqli_
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Source: http://www.php.net/manual/en/mysqli-result.fetch-array.php

$query = mysql_query("SELECT * FROM table WHERE name = $name");
$result = mysql_fetch_array($query);
//you'll get value in var
$var=$result['content'];

You can do this using Prepared Statements :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($value_you_want, $value_you_want_as_well);
while($stmt->fetch()){
echo $value_you_want . $value_you_want_as_well;
}
$stmt->close();
Or you can do this using PDO :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = :name";
$stmt = $connection->prepare($query);
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 20);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $page) {
echo $page->whatever1 . $page->whatever2;
}
$stmt = null; // Set to null to destroy connection

Related

How works php date BETWEEN

I have a query and works:
$sql2 = "SELECT id FROM table WHERE '2022-06-06' BETWEEN date(se_from) AND date(se_to)";
But when the date is dynamic the query fails:
$pick_date = '2022-06-06';
$sql2 = "SELECT id FROM tblseasons WHERE $pick_date BETWEEN date(se_from) AND date(se_to)";
Can't understand, can anyone explain.
Thanks
Your query lacks parentheses in the date (so it fails to do what you want as the query will be invalid)
For security, please use parameterized prepared statement to avoid SQL injection attacks instead
For mysqli, it will be:
$conn = mysqli_connect("localhost", "user", "dbpass", "dbname1");
$pick_date = '2022-06-06';
$sql2 = "SELECT id FROM tblseasons WHERE ? BETWEEN date(se_from) AND date(se_to)";
$stmt = $conn->prepare($sql2);
$stmt->bind_param("s", $pick_date);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
while ($row = $result->fetch_assoc()) {
echo $row['id'] . "<br>"; // if you want to see the result;
}
For PDO, it will be
$dbh = new PDO('mysql:host=localhost;dbname=dbname1', "user", "dbpass");
$pick_date = '2022-06-06';
$string1 = "SELECT id FROM tblseasons WHERE :pick_date BETWEEN date(se_from) AND date(se_to)";
$stmt = $dbh->prepare($string1, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute([':pick_date' => $pick_date]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["id"] . "<br>"; // if you want to see the result;
}

Select All MySQL Rows

I have the following code which choose all rows in MYSQL but it show the last row only
$query = mysql_query("SELECT * FROM `users`") or die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$token = $row['instagram_access_token'];
}
echo "$token";
Your code echo last row because, within while loop every time you overwrites $token value with new value. Try to connect using PDO & assign variable to array like this.
$token=[];
$user='your_user_name';
$pass='your_password';
$conn= new PDO('mysql:host=your_host_name;dbname=your_db_name', $user, $pass);
$query = $conn->prepare('SELECT * FROM `users`');
$query->execute();
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$token[] = $row['instagram_access_token']; // see this line with []
}
echo '<pre>';
print_r($token);
echo '</pre>';
Note: Don't use mysql_* see more here Why shouldn't I use mysql_* functions in PHP?
Change your code to this:
$query = mysql_query("SELECT * FROM `users` ORDER BY RAND()") or
die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$m = $row['instagram_access_token'];
echo "$m";
}

PHP Fetch Associative Array - Selecting Multiple Rows from MySQL DB

Currently, I am able to select one row's data from my database table. I was wondering how it would be possible to select information from a specific different row without having to change the code to suit my needs every time. This is for a news article on my website.
Here's my Code:
<?php
session_start();
if(!$_SESSION['username']) {
header('location:index.php');
}
require 'connect.php';
$tbl_name = 'news';
$sql = "SELECT id, title, description, content FROM $tbl_name ORDER BY id DESC LIMIT 3";
$articles = array();
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ('<p class="sidenav">1. %s</p>',$row["id"],$row["title"]);
?>
Now, as you can see, I've selected 3 rows. How can I output data from more than one row? Currently, this will output nothing if I have more than one row. Is there a way to specifically pinpoint certain information without having to select a row with a specific id?
UPDATE:
I've gotten this code now, but what if I wanted to print more than one at a time?
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
printf ('<p class="sidenav">1. %s</p>',$row["id"],$row["title"]);
printf ('<p class="sidenav">2. %s</p>',$row["id"],$row["title"]);
printf ('<p class="sidenav">3. %s</p>',$row["id"],$row["title"]);
}
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
printf ('<p class="sidenav">1. %s</p>',$row["id"],$row["title"]);
}
I was able to accomplish this with the following code.
<?php
$i = 0;
$sql = "SELECT id, title FROM news ORDER BY id DESC LIMIT 3";
if ($stmt = mysqli_prepare($conn, $sql)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id, $title);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
$i++;
printf ('<p class="sidenav">' . $i . '. %s</p>',$id,$title);
}
/* close statement */
mysqli_stmt_close($stmt);
}
?>

Converting mysql into PDO format

I'm trying to convert some old php mysql code into PDO format but am stuck. I've looked at other posts on here but can't quite figure it out.
This is the old code:
<?php
if (isset($_POST['query'])) {
// Connect to database
mysql_connect("localhost", "xxxxx", "xxxxx");
mysql_select_db("xxxxx");
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = mysql_query("SELECT * FROM articles WHERE title LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql))
{
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
And this is what I've managed to do but think there's something wrong in the "while" part.
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
while ($row = $sql->fetchAll()) {
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
You are trying to call fetchAll on "sql" which is a string.
Now, you could use query but i suggest you to use prepare instead (for security reason, because you insert POST data).
$q = $conn->prepare("SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')");
$q->execute(array($query));
// result contains all returned data
$result = $q->fetchAll();
// or row by row
while($row = $q->fetch())
From PHP.net
foreach ($conn->query($sql) as $row) {
Try somehing like this:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
//Build Query - Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
$sth = $conn->query($sql);
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
=========Updated Answer========
//Better alternative
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')";
$sth = $con->prepare($sql);
$sth->bind_param("s", $query);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
PS: Best practice is to stick with prepared statements and execute for increased security.
Try to run this:
$rows = $conn->prepare("SELECT * FROM articles WHERE title LIKE ?")->execute(array('%'.$query.'%'))->fetchAll();
while($row = $rows->fetch()) {
// TODO: Parse the rows
}
Also, try not to use * in your queries, that's not the best practice, it is better to use a column list instead separated by commas, as you do not necessary need to load the values of all columns. select * is less scalable and it might be the source of security vulnerabilities, like accidentally loading the inappropriate column and passing its value to the inappropriate place.

php echo data from certain id

EDIT: I'm sorry I was unclear, I try to explain it right this time.
I have this data in a database table called tMenu:
id page_nl text
1 index_1 index1_text
2 index_2 index2_text
3 index_3 index3_text
These are 3 pages on my website called (in this case) index_1, index_2 and index_3. I have programmed it is such a way that each page shows there index1_text.
What I want now is to show page_nl in a menu. The code I have now is:
$qh = mysql_query('SELECT id, page_nl FROM tMenu ORDER BY id');
$row = mysql_fetch_array($qh);
$id = 'id';
<? echo $row['page_nl']; $id=="1" ;?>
<? echo $row['page_nl']; $id=="2" ;?>
<? echo $row['page_nl'];?>
In the way it is now it shows only page_nl from id 1, but I want that the next link shows page_nl from id 2. I hope my question is more clear now.
Your question isn't very clear - are you asking for something like this
$sql = "select * from yourtable where id = 1";
$result = mysql_query($sql);
//I am assuming there are more than 1 rows for ID 1
while($row = mysql_fetch_assoc($result)) {
echo $row['page_nl'];
}
OR ============================
$sql = "select * from yourtable"; //Select All
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
if($row['id'] == 1)
{
echo $row['page_nl'];
}
}
Presuming you mean database table, you need a routine to connect to the database then fetch the info:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "databasename"); // database name
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM table_name"; // put table name here
$result = $mysqli->query($query);
/* numeric array */
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["id"], $row["page_nl"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
You need to use a foreach($var as $key =>$value) loop

Categories