$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();
can somebody help me to this statement/syntax? i want the result as associative array (indexed by fieldname) and don't want to write this "$stmt->bind_result($name, $code);" statement. thanks
As you are not actually using any parameters i.e. ? then you dont really need to do a ->prepare
So you could just use the ->query() and ->fetch_assoc() mechanism
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
$result = $mysqli->query($query)
if ( $result === FALSE ) {
echo $mysqli->error;
exit;
}
/* fetch values */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row['name'], $row['code']);
}
After your comment
This is another option, if you have to keep the prepare
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
// there seems to be some confusion in the manual as to
// whether this next statement is needed or not
// see if that helps
$stmt = $mysqli->stmt_init();
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
if (!$stmt->execute()) {
echo $stmt->error;
exit;
}
$result = $stmt->get_result();
/* fetch values */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row['name'], $row['code']);
}
} else {
echo 'Failed to prepare statement';
exit;
}
The call to $stmt->get_result() basically converts a mysql_stmt object to a mysql_result object
Try this.
$stmt = $mySqli->query($query);
$countries = mysqli_fetch_all($stmt, MYSQLI_ASSOC);
$stmt->close();
Just try this :
while ($stmt->fetch(PDO::FETCH_ASSOC)) {
printf ("%s (%s)\n", $name, $code);
}
Related
I'm trying to pass row details as JSON. How can one separate the selected columns from the query
$SQLTask = "
SELECT priority
, task_name AS title
, task_description AS description
, start_date AS start
, end_date AS end
FROM t_tasks
"; -- removed extraneous semi-colon
$RESULT_Task = mysqli_query( $conn, $SQLTask );
while($ROW_TASK = mysqli_fetch_assoc($RESULT_Task))
{
$TASK_NAME = $ROW_TASK['title'];
$TASK_DESC = $ROW_TASK['description'];
$TASK_START = $ROW_TASK['start'];
$TASK_END = $ROW_TASK['end'];
}
$TASK_DETAILS[] = array('title' => $TASK_NAME, 'description' => $TASK_DESC, 'start' => $TASK_START, 'end' => $TASK_END);
mysqli_close($conn);
echo json_encode($TASK_DETAILS);
Tried it in the format below and it worked but I need to use the priority column for other queries.
The JSON is to feed a calendar and show events.
<?php
require('../classes/class_connect.php');
$Project_ID = $_GET['id'];
$SQLTask = "SELECT task_name AS title, task_description AS description, start_date AS start, end_date AS end FROM t_tasks WHERE project_id = " . $Project_ID . "";
$RESULT_Task = mysqli_query( $conn, $SQLTask );
while($ROW_TASK = mysqli_fetch_assoc($RESULT_Task))
{
$TASK_ARRAY[] = $ROW_TASK;
// if($ROW_TASK['priority'] == 'Low')
// {
// $eventClassNames = "bg-light-secondary";
// }
// else if($ROW_TASK['priority'] == 'Normal')
// {
// $eventClassNames = "bg-light-primary";
// }
// else if($ROW_TASK['priority'] == 'High')
// {
// $eventClassNames = "bg-light-warning";
// }
// else if($ROW_TASK['priority'] == 'Urgent')
// {
// $eventClassNames = "bg-light-danger";
// }
// array_push($TASK_ARRAY,$eventClassNames);
}
mysqli_close($conn);
echo json_encode($TASK_ARRAY);```
I am not sure whether I have clearly understood your question and what you want to achieve as to "How can one separate the selected columns from the query".
But as for the second part you illustrated since all you wanted was priority field you could drop all other fields from the query. Also you could add the eventClassNames within the query.
Try to use mysqli's fetch_all and see how it works. For the first part then you wouldn't have to loop through the result set to create an array unless there was further processing to the array https://www.php.net/manual/en/mysqli-result.fetch-all.php
$SQLTask = "SELECT priority,
case priority
when 'Low' then 'bg-light-secondary'
when 'Normal' then 'bg-light-primary'
when 'High' then 'bg-light-warning'
when 'Urgent' then 'bg-light-danger'
end AS eventClassName
FROM t_tasks WHERE project_id = " . $Project_ID . "";
$RESULT_Task = mysqli_query( $conn, $SQLTask );
$TASK_ROWS=$RESULT_TASK->fetch_all(MYSQLI_ASSOC);
$TASK_ARRAY=array_column($TASK_ROWS,'eventClassName');
echo json_encode($TASK_ARRAY);
<?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 LIMIT 3";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
echo json_encode($row)
Ref:https://www.php.net/manual/en/mysqli-result.fetch-array.php
i am developing a search option using php. there i need to do search using user given criteria user can be search when user give id,name,status any of combination of these three parameters.below is my code
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_POST['serviceNumber'])) {
$where[] = 'serviceNumber = ?';
$values[] = $_POST['serviceNumber'];
$types .= 'i';
}
if (!empty($_POST['name'])) {
$where[] = 'Username = ?';
$values[] = $_POST['name'];
$types .= 's';
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$types .= 's';
}
$query .= implode(' AND ',$where);
printf("rows inserted: %d\n", $query);
printf("rows inserted: %d\n", $values);
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
below line i was going confused,because $values is an array.i need to pass user given paremeters to this in order to execute.
$stmt->bind_param($types,$values);
so in order to get correct results how do i need to do this.
You can use call_user_func_array() to call a function with an array of parameters. The parameters need to be stored as references in order to be passed to the bind_param method. Long story short, you need an array where the 1st value is a string and the rest are references to your parameters.
For example:
$bindParams = [$types];
foreach ($values as $key => $value) {
$bindParams[$key] = &$value;
}
call_user_func_array(
[$stmt, 'bind_param'], //array with the object and the method - callable
$bindParams
);
Try using below:
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
if (!empty($_POST['serviceNumber'])) {
$query .="serviceNumber='$searchkey' ";
}
if (!empty($_POST['name'])) {
$query .="and Username='$name' ";
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$query .=" and status='$status' ";
}
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps.
I have code, which is basically a copy of a php.net's code, but for some reason it does not work. Here is the code on php.net:
<?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();
?>
The first change I made was the connection:
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
The second change I made was the queries:
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
EDIT: The full code with my changes
<?php
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
/* 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();
?>
The error I get:
Strict standards: mysqli::next_result(): There is no next result set.
Please, call mysqli_more_results()/mysqli::more_results() to check
whether to call this function/method in
address on line line number
I searched a solution over the net, and particularly here on StackOverflow, but I did not find helpful solutions. Most of the solutions I found were one of those two:
In this solution,#Hammerite says to change the loop from do-while to while. This suggest that php.net's code has a problem in its logic, and I find it very hard to believe. But more importantly, it just does not work for me.
In this solution, #mickmackusa suggests to add a condition in the while and change $mysqli->next_result() to $mysqli->next_result() && $mysqli->more_results(), but this solution do not work quite well. It does indeed removes the error but it omits the last result.
Try it with
} while ($mysqli->more_results() && $mysqli->next_result());
sscce:
<?php
ini_set('display_errors', 'on');
error_reporting(E_ALL|E_STRICT);
$mysqli = new mysqli("localhost", "localonly", "localonly", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query('CREATE TEMPORARY TABLE City (ID int auto_increment, `Name` varchar(32), primary key(ID))') or die($mysqli->error);
$stmt = $mysqli->prepare("INSERT INTO City (`Name`) VALUES (?)") or die($mysqli->error);
$stmt->bind_param('s', $city) or die($stmt->error);
foreach(range('A','Z') as $c) {
$city = 'city'.$c;
$stmt->execute() or die($stmt->error);
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (!$mysqli->multi_query($query)) {
trigger_error('multi_query failed: '.$mysqli->error, E_USER_ERROR);
}
else {
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->more_results() && $mysqli->next_result());
}
prints
'localonly#localhost'
-----------------
'cityU'
'cityV'
'cityW'
'cityX'
'cityY'
without warnings/notices.
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
Hi I have the following code below in a php file
global $server, $mysqlusername, $mysqlpassword, $db;
$conn = new mysqli($server, $mysqlusername, $mysqlpassword, $db);
function getCategories() {
global $conn;
$categories = array();
$sql = "SELECT categoryName FROM reportcategorys";
$maincat = $conn->query($sql);
while($row = $maincat->fetch_array(MYSQLI_ASSOC)) {
// do something with the $row
array_push($categories, $row);
}
$sql1 = "SELECT * FROM reportsubcategorys";
$subcats = $conn->query($sql1);
// Loop through sub categories and append to parent array
while($row = $subcats->fetch_array(MYSQLI_ASSOC)) {
$parent = $row['categoryName'];
$name = $row['subCategoryName'];
// Append subcategory name as child to the parent category
for ($i=0; $i<count($categories); $i++) {
if ($categories[$i]['categoryName'] == $parent) {
array_push($categories[$i], $name);
}
}
}
//print_r($categories);
return $categories;
}
It is giving me an error message saying
"Fatal error: Call to a member function fetch_array() on a non-object in"
Any idea what may be causing this?
Thanks
It is likely that your query has not executed properly.
mysqli->query() will return a boolean value FALSE if the query has not been executed properly, else it will return a mysqli_result object. So after every query, before calling fetch_array() method, check the result of the query. Something like this.
$maincat = $conn->query($sql) or die($conn->error);
or
$maincat = $conn->query($sql);
if(!$maincat){
echo $conn->error;
}
Also, when you established your connection with the database, check if the connection was error-free.
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
Are you using fetch_array for any reason in particular?
Try it like this one...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* verificar la conexión */
if (mysqli_connect_errno()) {
printf("Conexión fallida: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* obtener array asociativo */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* liberar el resultset */
$result->free();
}
/* cerrar la conexión */
$mysqli->close();
?>