PHP/MySQL to PDO? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm very new to PHP/Mysql and I naturally have a few questions. I was following a youtube tutorial on creating a simple dynamic website that pulls data content from a MySQL database then displays the content on a single PHP index page. I followed this tutorial to the point where I was using PHP/MySQL to connect to the DB, run a query, fetch the query using a fetch_assoc array. but nothing would display in the body of the page. During the trouble shooting process I was advised that I should be using PDO instead of the older MySQL methods. Can someone decipher my current "older" MySQL code and translate it into the proper PDO coding approach so that I can learn to grasp PDO, since it is the future I should start to understand it now :)
index.php:
<?php
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?> - test site</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header">
<?php include('template/header.php'); ?>
</div>
<div class="nav_main">
<?php include('template/nav_main.php'); ?>
</div>
<div class="content">
<?php //include('content/'.$pg.'.php');
// the database connection, our query
$q = "SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
if (!$r) {
die('Invalid query: ' . mysql_error());
}
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
?>
</div>
<div class="footer">
<?php include('template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php:
<?php ## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "localhost";
$username = "atomcmsadmin";
$password = "uniCi2i";
$dbname = "Atom_CMS";
//Connecting to your database
$dbc = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysqli_select_db($dbname);
//include('functions/sandbox.php');
if ($_GET ['page'] == '') {
$pg = 'home';}
else {
$pg = $_GET ['page']; }
$page_title = get_page_title($dbc, $pg);
?>
sandbox.php
<?php
// Sandbox Functions
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';
}
function get_page_title ($dbc, $pg) {
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
return $page['title'];
}
?>

http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
all you need to change is setting up the connection, check out the tutorial for the syntax
interacting with the database is still mostly the same

I think no one will do the job for you. But I can help you help yourself:
From your code, you'll need to learn these PDO methods:
PDO::__construct()
You'll replace mysqli_connect() and mysqli_select_db() with that.
PDO::prepare(), PDOStatement::bindValue() and PDOStatement::execute()
You'll replace mysqli_query() with them.
PDOStatement::fetch()
You'll replace mysqli_fetch_assoc() with that.
PDO::errorCode() and PDO::errorInfo()
You might want to use one of them or both to cover errors.
Also take a look at PDO book on the PHP manual. You'll learn all the stuff more easier than you think! Good luck!

Related

Search bar wont return results [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Cant figure out what's going wrong here, no errors are appearing but nothing is being returned. The search bar should return the names of other users from my database.
Here is Test.php:
<?php
session_start();
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({
url:"PHP.php",
type:"POST",
data {partialSearch:partialSearch},
success:function(result){
$("#results").html(result);
}
});
};
</script>
</head>
<body>
<div class="container">
<h3>Find Other users</h3>
<input type="text" name="partialSearch"onkeyup="search(this.value)"/>
<div id="results"></div>
</div>
</body>
</html>
Here is PHP.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "coursework_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$partialSearch = $_POST['partialSearch'];
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($row = $stmt->fetch()) {
$searchResults[] = $username;
echo "<div>".$searchResults."</div>";
}
?>
Here is the SQL table:
CREATE TABLE members (
memberID int(5) NOT NULL AUTO_INCREMENT,
username VARCHAR(65) NOT NULL UNIQUE,
password VARCHAR(65) NOT NULL,
PRIMARY KEY (memberID)
);
Thank you in advance for any help!
Besides the missing colon in
data {partialSearch:partialSearch},
^
which should read as:
data: {partialSearch:partialSearch},
Your PHP/MySQL syntax is off.
You're declaring $row in
while ($row = $stmt->fetch())
but not using it anywhere.
However, that's kind of a bad for a good as you don't need that much code to start with.
Plus, since you're using LIKE, you're not using the right syntax for it.
See the manual on this: http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html
What your code should look like is this:
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
echo $username;
echo "<div>".$searchResults."</div>";
}
Having checked your console and for errors, you'd of seen what was going on or not.
The JS console would have thrown you:
SyntaxError: missing : after property id
If that still doesn't work for you, then you most likely have errors in your database somewhere.
Consult:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
you seem tyo be using $username twice-
first for the database access
$username = "root";
and then to reference the database results
$stmt->bind_result($username);
which would seem to cause a conflict since $username="root" - try changing the name to a different variable and see if that makes a difference; eg:
$stmt->bind_result($user_name);
also you have not declared $searchResults to be an array before pushing elements into it, add the following before the while loop:
$searchResults = array();
Concatenate $partialSearch with % wildcards.
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? ");
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt->bind_param('s',$partialSearch);
...
you are also missing a ":" in the Ajax query - should be:
data: {partialSearch:partialSearch},

mySQL dropdown using PHP does not display options from database [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I looked at some other questions online and on here related to this, but none seem to really encounter my error exactly.
I wrote my PHP code and implemented it into my HTML, I get the dropdown box appearing, but it doesn't actually want to display any values. Is there any implementations or fixes I should include in my code? How do I get it to work?
My database is called: Treatments
My column in the database that I want displayed is called: Treatment
treatment_dropdown.php
<?php
$hostname = 'host_name';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
$con=mysql_connect($hostname,$username,$password,$dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = "SELECT * FROM `Treatments`";
$result = mysql_query($con, $query);
$options = "";
while ($row = mysql_fetch_array($result)){
$options = $options . "<option>$row[1]</option>";
}
?>
HTML:
<body>
<select>
<?php
echo $options;
?>
</select>
</body>
Consider changing this line:
$query = "SELECT * FROM 'Treatments'";
to use backticks instead of single quotes like so:
$query = "SELECT * FROM `Treatments`";
In my test query I got an error because of this, let me know if that helps.
Add <?php include 'treatment_dropdown.php'; ?> to the top of your HTML file. This should give you access to the the $options string so it can be used in that file. Note that in order for this to work, treatment_dropdown.php needs to be in the same directory as your HTML file. If it is not, the include statement will need to be changed to reflect the appropriate file path.
Do not use mysql_*() functions, they are deprecated. Use mysqli or PDO instead.
No matter which library use use to access mysql, always check for errors within the sql code separately. Errors in the sql code do not result in errors in the php code.
In this particular case the problem is that you included the table in single quotes instead of backticks.
The correct code:
$query = "SELECT * FROM `Treatments`";
Here's what your PHP file should look like:
<?php
$hostname = 'localhost';
$dbname = 'Treatments';
$username = 'root';
$password = '';
$con = mysql_connect( $hostname, $username, $password, $dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
/* No single quotes needed for the table name. */
$query = "SELECT * FROM Treatments";
/* First parameter should be $query not $con */
$result = mysql_query($query, $con);
$options = "";
/* Check if no results exist. */
if ( !$result ) {
die( "NO results found." );
}
while ( $row = mysql_fetch_array($result) ) {
$options .= "<option>$row[treatment]</option>";
}
?>
Notes:
dont use mysql_* functions, they're not secure, use PDO instead.
your table name does not need to be wrapped in single quotes.
mysql_query expects parameter 1 to be the query not the DB connection.
you should probably check if no results are found.

Searching multiple rows in MySQL database with PHP

I am trying to create an "explore" page on a site I am developing at the minute. Here are images of the page and the database for visual reference.
Database: http://gyazo.com/a48eb00458d3a93845bc666af23775c1
Webpage: http://gyazo.com/69d0889c77d784d12448827b603891be
Here is my current PHP Script:
$connect = mysql_connect("localhost","root","root");
if (!$connect) {
die('lel' . mysql_error());
}
$search = $_GET['make'];
mysql_select_db("dapper");
$query = mysql_query("SELECT * FROM posts WHERE make = '$search'");
while ($rows = mysql_fetch_array($query)) {
$id = $rows['id'];
$photographer = $rows['photographer'];
$carowner = $rows['car-owner'];
$make = $rows['make'];
$event = $rows['event'];
$author = $rows['author'];
$date = $rows['date'];
echo "
<article>
<img src='uploads/$id.jpg'>
</article>";
}
fclose($connect);
?>
And here is my HTML markup for searching:
<ul>
<h4>Make</h4>
<li>Vw</li>
<li>Audi</li>
</ul>
<ul>
<h4>Event</h4>
<li>H20i</li>
<li>Titanic Dubs</i></li>
<li>Dubshed</li>
<li>Players Show</i></li>
</ul>
As you can see from the webpage image the user should be able to search for events, makes and photographers. However I have only managed to get the script to successfully search for one thing. I feel I haven't explained this the best but I am NOT trying to allow the user to search for eg: photographers and events in the same search.
Thanks in advance.
Jamie McArdle,
PHP Noob
As per OP to close the question:
$search2 = $_GET['event']; - WHERE make = '$search' OR event = '$search2' or by replacing OR with AND if your rows match what you have in your present rows for those criterias.
A suggestion:
You may be best using dropdown menus or radio buttons, then using the values instead of multiple href's.
That way, your page won't be filled with links, should the criterias grow larger over time.
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
I suggest you look into mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Edit:
For results or not:
if($query){
while ($rows = mysql_fetch_array($query)) {
$id = $rows['id'];
$photographer = $rows['photographer'];
$carowner = $rows['car-owner'];
$make = $rows['make'];
$event = $rows['event'];
$author = $rows['author'];
$date = $rows['date'];
echo "
<article>
<img src='uploads/$id.jpg'>
</article>";
}
}
else{
echo "No results.";
}

My first PHP/MySQL db, no output to the webpage?

I'm a noob to PHP/mySQL and I'm enjoying it, but I'm stuck... I'm in the process of developing my first database driven website. I've created the database, the tables... loaded one table in particular with content in an attempt to pull data from it via PHP. If you go to my website live via the browser, there is a navigation system that seems to work but, it's not loading content from the db table. It's just blank content with a nav system that changes the page in the address bar but blank content. I've provided the code along with a image shot of the table in my database I'm trying to GET the data from. The db table i'm getting from is called vls_pages. It is also the table featured in the image. I'm hoping someone can point me to getting this to function correctly. Thank you everyone
index.php CODE:
<?php
// Load Setup document:
include
('_config/setup.php'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?></title>
<link rel="stylesheet" type="text/css" href="_css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="nav_main">
<?php include('_template/nav_main.php'); ?>
</div>
<div class="body_header">
<?php get_page_name($dbc, $pg); ?>
</div>
<div class="content">
<?php get_page_body($dbc, $pg); ?>
</div>
<div class="footer">
<?php include('_template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php CODE:
<?php
## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "***************";
$username = "***************";
$password = "***************";
//Connecting to your database
$dbc = #mysqli_connect($hostname, $username, $password) OR DIE ("Unsuccessful.");
// Check connection
if (mysqli_connect_errno($dbc))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
include('_functions/snippets.php');
if ($_GET['pgname'] == '') {
$pg = 'home';
}
else {
$pg = $_GET['pgname'];
}
$page_title = get_page_title($dbc, $pg);
?>
snippets.php CODE:
<?php
// Snippets; Functions
function get_page_title ($dbc, $pg) {
$query = "SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
return $page['pgtitle'];
#mysqli_close($dbc);
}
function get_page_name ($dbc, $pg) {
$query = "SELECT pgname FROM vls_pages WHERE pgname = '$pg' AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
echo '<h1>'.$page['pgname'].'</h1>';
#mysqli_close($dbc);
}
function get_page_body ($dbc, $pg) {
// the database connection, our query
$query = "SELECT * FROM vls_pages WHERE pgbody = '$pg' AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
echo '<div class="content">'.$page['pgbody'].'</div>';
#mysqli_close($dbc);
}
?>
You're closing the database connection at the end of each function. So after you get the page title, the database connection closes.
Remove this line from the end of every function in setup.php:
#mysqli_close($dbc);
Then add that line to the end of index.php to close the connection after the page is done processing:
<?php
mysqli_close($dbc);
?>
This will solve the major issue described in the question. For the sake of completeness, you should also follow the recommendations in the comments area of the question. Specifically, the SQL query in get_page_title() should have "WHERE" instead of "AND", and remove the "#" error suppression, especially while you're learning.
there is a mistake in your query, you forgot to keep where condition please replace the following code
$query = "SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1";
with
$query = "SELECT pgtitle FROM vls_pages where pgstatus = 1 LIMIT 1";
As per the SELECT syntax in the manual on the MySQL.com website.
The syntax is SELECT select_expr FROM table_references WHERE where_condition equals
Now, this line is using the AND clause:
SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1
which should be using the WHERE clause, such as:
SELECT pgtitle FROM vls_pages WHERE pgstatus = 1 LIMIT 1
Consult lwitzel's answer also
Food for thought:
Do take the comments into (serious) consideration when it comes to properly sanitizing your inputs.
The use of PDO is highly recommended - PDO Tutorial

$result = mysql_query()

I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli

Categories