I have a couple of questions here, so any help will be greatly appreciated. I have three pages here.
//Page 1 - Constants
$dbhost = "database.url.com"; //Just made up
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "123456";
//Page 2 - The Function
//This is where i need to write the function select information from the database.
include ("include/page1.php");
$DBH = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
function selectInfo(){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
}
//This function obviously is not complete because I keep recieving different error messages. I guess i cannot figure out how to write a prepared select statement. Need some help here.
//Page 3 - Where the function is called and where the user would be
include ("include/page2.php");
//need to be able to call the function here with variables set.
$start = 0;
$end = 5;
selectInfo();
echo the data that i need in the database.
This probably looks like a complete mess, but hopefully you can get the idea i am trying to do here. I would like to be able to fetch the data so that i can display it something like
echo $stmt->title;
echo $stmt->id;
if that is possible. Can anyone please help me?
You need to execute the bind_param and execute method on your mysqli object:
$DBH->bind_param("ii", $start, $end);
And then execute the statement:
$DBH->execute();
Just have a close look at the mysqli API.
From php.net first example.
<?php
$mysqli = new mysqli("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 DESC LIMIT 150,5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
#mcbeav
You should change your function:
function selectInfo(){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
}
To something like this:
function selectInfo($limit, $offset){
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
// Other stuff to get your values from this query
...
// Return the object with the results
return $values;
}
Everything you need is explained in the mysqli_prepare documentation.
Related
I want to get information by user id, so lets add this to the model:
public function getById ($id)
{
$sql = 'SELECT * FROM users';
return ActualDbHander::run($sql);
}
later, I want to get only some fields:
public function getById ($id, $fields = '*')
{
$sql = 'SELECT '.$fields.' FROM users';
return ActualDbHander::run($sql);
}
another idea, lets add ordering:
public function getById ($id, $fields = '*', $orderBy = '')
{
$sql = 'SELECT '.$fields.' FROM users';
if ($orderBy != '')
{
$sql.= ' ORDER BY '.$orderBy;
}
return ActualDbHander::run($sql);
}
and I see this becaming messy and messy. What if I want to add JOIN-s? What if I want to add detailed WHERE-s? This is when "too generalic" methods born.
I completely agree with mch and Mjh comments, but, only in the case you actually want to have a "BD driver" (and build it yourself) I'd use different names for each query, very specific names, because you need to know exactly what a function will return to you.
So if I were you I would use names like getAllUsers, getUserById, getAllUsersOnlyPersonalData, getUserByIdOnlyPersonalData, getAllUsersOnlyContactData and so on (with fixed fields and filters for each method).
Note that in your examples you are not using at all the $id variable, so you are always receiving a list of users.
Regarding the method to make the queries, there are lots of ways to do it. Personally, I prefer MySQLi Object-Oriented prepared statements, because it's safe, easy and currently very extended, so I will use it just to ilustrate the examples.
Your functions would be something like this:
<?php
class DBDriver{
function openConnection(){
// If you don't always use same credentials, pass them by params
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Return conection object
return $conn;
}
function closeConnection($conn){
$conn->close();
}
function getAllUsers (){ // We don't need ids here
$conn = $this->openConnection();
// Array of arrays to store the results
// You can use any other method you want to return them
$resultsArray = [];
$sqlQuery = "SELECT * FROM users";
// In this case it's not neccesary to use prepared statements because we aren't binding any param but we'll use it to unify the method
if ($stmt = $conn->prepare($sqlQuery)) {
// Execute query
$stmt->execute();
// Bind result variables (I don't know your actuall column names)
$stmt->bind_result($id, $name, $email, $phone, $birthdate);
// Fetch values
while ($stmt->fetch()) {
$resultsArray[] = [$id, $name, $email, $phone, $birthdate];
}
// Close statement
$stmt->close();
}
$this->closeConnection($conn);
// If no results, it returns an empty array
return $resultsArray;
}
function getUserByIdOnlyContactData ($userId){
$conn = $this->openConnection();
// Array to store the results (only one row in this case)
$resultsArray = [];
$sqlQuery = "SELECT name, email, phone FROM users WHERE id = ?";
if ($stmt = $conn->prepare($sqlQuery)) {
// Bind parameter $userId to "?" marker in $sqlQuery
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($name, $email, $phone);
// If id found
if ($stmt->fetch()) {
$resultsArray = [$name, $email, $phone];
}
// Close statement
$stmt->close();
}
$this->closeConnection($conn);
return $resultsArray;
}
function getAllUserOnlyBirthdayDataOrderByBirthday (){
$conn = $this->openConnection();
$resultsArray = [];
$sqlQuery = "SELECT id, name, birthdate FROM users ORDER BY birthdate";
if ($stmt = $conn->prepare($sqlQuery)) {
$stmt->execute();
$stmt->bind_result($id, $name, $birthdate);
while ($stmt->fetch()) {
$resultsArray[] = [$id, $name, $birthdate];
}
// Close statement
$stmt->close();
}
$this->closeConnection($conn);
return $resultsArray;
}
} // Class end
This way it's true you will have lots of functions depending on your requirements but as you can see it's extremely easy to add new ones or modify them (and you won't get mad with many different options in the same function).
Hope this helps you to organize your database driver!
I'm converting to Mysqli object-oriented (or trying to). I have various category pages. I'd like to use a parameter placeholder '?' in the include and then call up the right category on the category page.
This is as far as I've gotten. How do I indicate the category on my page? All works fine if I indicate WHERE category = apples.
I have this include at top of a category page
<?php require_once 'maincats_mysqli.php' ?>
which is below:
<?php
$db = new mysqli('host', 'userName', '', 'dbName');
if ($db->connect_error) {
$error = $db->connect_error;
} else {
$sql = "SELECT pageName, gImage, prodName, prodPrice
FROM tableName
WHERE category = '?'
ORDER BY dtList DESC";
$stmt->bind_param('s', ['$category']);
$result = $db->query($sql);
if ($db->error) {
$error = $db->error;
}
}
function getItem($result) {
return $result->fetch_assoc();
}
?>
Below is part of one category page. How do I indicate which category? Any help would be appreciated.
<?php
if (isset($error)) {
echo "<p>$error</p>";
}
?>
<?php
while ($item = getItem($result)) {
?>
<a href="http://www.example.com/<?php echo $item['pageName']; ?>">
<img src="http://www.example.com/<?php echo $item['gImage']; ?>"</a>
<a href="http://www.example.com/<?php echo $item['pageName']; ?>">
<?php echo $item['prodName']; ?></a>
<?php echo $item['prodPrice']; ?>
<?php
}
?>
First, you don't declare $stmt.
Second, ? is not a wildcard in this case, it's a parameter placeholder. You can use such placeholders when preparing the query, with $mysqli->prepare($sql). See documentation: http://php.net/manual/en/mysqli-stmt.bind-param.php
$sql = "SELECT pageName, gImage, prodName, prodPrice
FROM tableName
WHERE category = ?
ORDER BY dtList DESC";
$stmt = $db->prepare($sql);
Third, you encapsulate your variable in single quotes, so it's a string with a dollar and the name of your variable, not its content. And it must not be in an array:
$stmt->bind_param('s', $category);
Last: where does $category comes from? It's not defined in the script you show us. I guess it's from $_GET, so the previous line should be:
$stmt->bind_param('s', $_GET['category']);
Finally, you need to execute your statement, which contains the query:
$stmt->execute();
EDIT:
To fetch results, you don't need that getItem() function. Just remove it.
$result = $stmt->get_result();
Then you can loop over $result and fetch each row:
while ($item = $result->fetch_assoc()):
// do you stuff
endwhile;
Note that I use here the PHP control structure alternative syntax which is more clear in your case (endwhile is more explicit than just })
You're missing the prepare(). Look at the first example in the PHP manual page:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Note that you must not quote binded parameters.
I have a little problem, I have been testing numbers of variants but I don´t get it to work.
I have a link in the search result.. (Full text search working)
> while($row = mysql_fetch_assoc($query)){
>
> $id = $row['id'];
>
> echo '<a href=profile1.php?id= . $row["id"] . >.INFO.</a>';
It shows INFO as a link and when i click on it, i jump to profile1.php but I´m not seeing any results, it is totaly blank page. the url I get is .../profile1.php?id=
Here is my profile.php
<?php
$mysqli = new mysqli("", "", "", ""); /* REPLACE NECESSARY DATA */
/* ESTABLISH CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id=$_GET["id"];
if ($stmt = $mysqli->prepare("SELECT name, brand FROM table WHERE id=?")) {
$stmt->bind_param("d", $id); /* BIND DATA TO QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($name, $brand); /* BIND RESULT TO VARIABLE */
$stmt->fetch(); /* FETCH DATA */
printf("%s - %s", $name, $brand); /* ECHO DATA */
$stmt->close(); /* CLOSE STATEMENT */
}
$mysqli->close();
?>
I hope someone can help me.. Thanks!!!
Do this .
echo "<a href=profile1.php?id=$row[id]>INFO</a>";
or this.
echo '<a href=profile1.php?id='.$row['id'].'>INFO</a>'
Note:
You assigned your id to a variable, so better use that variable to the link. You should learn how to incorporate variables to your link.
Better use a single tick (') when using a variable inside. It's okay not to use single tick (') in your query IF the variable you are binding is an integer type.
Your link should look like this:
$id = $row['id'];
echo '<a href="profile1.php?id='.$id.'" >.INFO.</a>';
And your select query should look like this (profile1.php):
$sql ="SELECT * FROM table WHERE id='".$_GET["id"]."'";
It is also recommendable to use mysqli_* rather than the deprecated mysql_* API. Read here to learn more about SQL injections.
If you had it into mysqli_* prepared statement, it would look like this (profile1.php):
<?php
/* RE-ESTABLISH YOUR MYSQL CONNECTION */
$con = new mysqli("YourHost", "yourUsername", "YourPassword", "YourDB"); /* REPLACE NECESSARY DATA */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $con->prepare("SELECT name, brand FROM table WHERE id = ?")){
$stmt->bind_param("i", $_GET["id"]); /* PARAMETIZE GET ID TO QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($name, $brand); /* BIND RESULT TO VARIABLE */
$stmt->fetch(); /* FETCH DATA */
printf("%s - %s", $name, $brand); /* ECHO DATA */
$stmt->close(); /* CLOSE STATEMENT */
}
$con->close();
?>
I want to create a php script using prepared statements to query a table in my database and return the results in json format. I have a table of doctors and i want to return the doctors of a given speciality. I have a version of the script that doesn't use prepared statements that works fine. But when i use prepared statements my script doesn't work.
Non - prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality='$speciality'";
$result = $mysqli->query($query) or die("Error executing the query");
while($row = $result->fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$mysqli->close();
?>
prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality=?";
if ($stmt = $mysqli -> prepare($query)){
$stmt -> bind_param("s", $speciality);
$stmt -> execute();
$result = $stmt -> get_result();
while($row = $result -> fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$stmt -> close();
} else {
echo $mysqli->error;
echo "no entry found";
}
$mysqli->close();
?>
What am i doing wrong? I don't get a mysqli error which means that the problem is after the execution of the query but i just don't know what it is.
Edit: What i mean by saying it doens't work is that i don't get anything back. The html body of the page after the execution is completely empty. On the other hand if i use the other script i posted (without prepared statements) i get the expected result.
UPDATED:
Use this:
/* bind result variables */
$stmt->bind_result($col1,$col2,$col3,$col4);
/* fetch values */
while ($stmt->fetch()) {
$output[]=array($col1,$col2,$col3,$col4);
}
Instead. Hope it helps.
anyone please give reason of putting downvote.
ini_set('display_errors',1);
error_reporting(E_ALL);
and then look at HTML body again. Most likely get_result is not supported but I hate to guess.
Make sure your version of PHP is compatible with the method
http://php.net/manual/pt_BR/mysqli-stmt.get-result.php
To get data as associative array you can do as follow:
$stmt->bind_result($col1, $col2);
$rows = [];
while ($stmt->fetch()) {
$rows[]=array("col1"=>$col1, "col2"=>$col2);
}
I am having a problem with mysqli. I am trying to search a database for all people who meet a category. While looping through the results, I want to create an instance of a "Person" class, passing the database connection to the class. This is where the problem starts. Here is my code.
$con = new mysqli($db_host,$db_user,$db_password,$db_name);
if (mysqli_connect_errno())
{
die(mysqli_connect_error()); //There was an error. Print it out and die
}
$sql = "SELECT id FROM users";
$stmt = $con->prepare( $sql );
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch())
{
$person = new Person( $con );
}
$stmt->close();
}
If i move the $person = new Person( $con ); to just after the while loop, it successfully makes an object of the last person. It just won't work when inside the loop. What is the reason for this?
According to error shown, you can't use the same connection until previous result set is in use. In order to make it work, you can do something like this:
$personIDs = array();
while($stmt->fetch())
{
$personIDs[] = $id;
}
$stmt->close();
and than just go through all ids buffered into array:
foreach($personIDs as $id) {
$person = new Person( $con );
}
Or, you can use store_results
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_results();
while($stmt->fetch())
{
$person = new Person( $con );
}
$stmt->free_result();
$stmt->close();
}