Is it okay to use while when fetching data using php + MySQLi? - php

Is it okay to use while when fetching data using php + MySQLi? Can it be prerequisite for any obvious issues?
$getpost->bind_result($returned_post);
while($getpost->fetch()){
echo($returned_post);
}

is normal when mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....
see this example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
you can read more in:
http://php.net/manual/en/mysqli-stmt.bind-result.php

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

In PHP & MySql programming how to executive more then 3 queries in a single statement?

i want to execute a more then 3 queries in a single statement.
is is possible?
i need to insert the values into the table
select entire table
count the users.
is it possible to do all these in a single statement.
Thanks
You can use more than 3 queries only in mysqli using mysqli_multi_query(), but mysql doesn't support it.
Example code :
<?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 CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Change it accordingly. It shows multiquery in action using mysqli.

Example php code for connecting and getting a sql stored proceedure

Can any one give
The Example php code for connecting and getting a sql stored proceedure
what do you prefer to use? Here is an example taken from php.net:
$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 = "CALL get_items(1, #param1, #param2); ";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
remember, that you have to free the resultset, if you do not, you will get an error while executing a next query.
Before I know something about mysqli, I apply mysqli to handle sp's. Just take a look at the follwing example:
$rs = mysql_query("CALL get_items(1, #param1, #param2); ");
$rs = mysql_query("SELECT #param1, #param2" );
while($row = mysql_fetch_assoc($rs))
{
print_r($row);
}
Calling a Stored procedure with PDO

Categories