PHP MySQLI Object-Oriented with Wildcard - php

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.

Related

Determine if PHP mysqli fetch returns data or not

I'm trying to take the following code from the PHP website and rewrite to echo out if the returns my SQL data is null.
<?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 */
if ($stmt = $mysqli->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();
?>
I'm having issues figuring out the right conditional to do this. Just looking for idea's on how to further optimize this code.
$rows = $stmt->rowCount();
echo $rows;
If you are trying to find out whether $district variable is null after the execution of the SQL query, you can try:
if(!empty($district)){
//code if there is a value
}
else{
//code if it is null
}
If you are sure that the database returns null if not found, you can use !is_null($district) instead of !empty($district).

PHP link in search results not working correct

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();
?>

PHP MySQLI prepared statement breaks at get_results()

I am very new at mysqli prepared statements, in fact this is my first try at it. I have this block of code and I put echos inbetween each command, and it displays aaa and bbb but not ccc, what am i doing wrong here?
no errors come up, just a blank screen:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT title FROM `in-the-press`")) {
$stmt->execute();
echo 'aaa';
$stmt->bind_result($title);
echo 'bbb';
$result = $stmt->get_result();
echo 'ccc';
while ($stmt->fetch()) {
printf("%s %s\n", $title);
}
echo 'ddd';
$stmt->close();
}
$mysqli->close();
?>
UPDATE I was able to get this working, by doing the following:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT id, community, map, image FROM `googleMaps`")) {
$stmt->execute();
$stmt->bind_result($id, $community, $map, $image);
$stmt->fetch();
printf($id . ' ' . $community . ' ' . $map . ' ' . $image);
$stmt->close();
}
?>
but this only gives me 1 row of data, how do I get all rows of data?
To use get_result() you must use the mysqlnd driver. This is enabled by default in PHP 5.4 and later. If you're using an earlier version of PHP, you have to do some installation to get mysqlnd to work. See http://php.net/manual/en/mysqlnd.install.php
If you use get_result(), then you don't need to bind anything. You just fetch each row as an array, and reference the columns as elements of that array:
if ($stmt = $mysqli->prepare("SELECT title, community, map, image FROM `googleMaps `")) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
printf("%s %s\n", $row["title"], $row["community"]);
}
$stmt->close();
}
If you don't use get_result(), you use Mysqli in the old manner, binding variables to columns, and calling fetch() to populate the variables. But you need to run a loop until fetch() returns NULL when the result is finished.
if ($stmt = $mysqli->prepare("SELECT title, community, map, image FROM `googleMaps`")) {
$stmt->execute();
$stmt->bind_result($title, $community, $map, $image);
while ($stmt->fetch()) {
printf("%s %s\n", $title, $community);
}
$stmt->close();
}
You need to print your results in a loop, for instance you need to echo for each result found.
http://php.net/manual/en/control-structures.for.php

PHP - prepared statements and json_encode

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);
}

Need Help With mysqli PHP select Statement

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.

Categories