Can't we call $result as variable in php - php

i have query in my php code
$dbc = mysqli_connect('localhost', 'root','', 'delivery')
or die('Error connecting to MySQL server.');
$count = "SELECT MAX(id_pelanggan) FROM pelanggan";
$result = mysqli_query($dbc, $count)
or die('Error select query');
if (empty($result)) {
$id_pelanggan = 1;
}
else {
$id_pelanggan = $result + 1;
}
and the result was
Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\delivery\addcustomer.php
whereas in mysql id_pelanggan datatype is int.
can anyone help me to make it works?

You try to assign your query to $id_pelanggan variable instead of the value from your query.
Fetch the result using *_fetch array() of your query
I've changed your if() condition because your $result won't be empty no matter what happens. The number of result maybe.
Put this and replace your if else condition:
if(mysqli_num_rows($result) == 0){ /* IF FOUND 0 RESULT */
$id_pelanggan = 1;
}
else {
while($row = mysqli_fetch_array($result)){
$maxid = $row["id_pelanggan"];
}
$id_pelanggan = $maxid + 1;
} /* END OF ELSE */

Simple fetch the result and increment it. You can do this by -
$count = "SELECT MAX(id_pelanggan) as max_id_pelanggan FROM pelanggan";
$result = mysqli_query($dbc, $count)
or die('Error select query');
if (empty($result)) {
$id_pelanggan = 1;
}
else {
$data = mysqli_fetch_assoc($result);
$id_pelanggan = $data['max_id_pelanggan'] + 1;
}

Related

Using multi_query doesn't give the desired output

I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated.
$mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314);
if(!$mysqli){
die('Connection failed!');
}
$sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`";
$sql .= "SELECT index, polievka, cena FROM `polievky`";
$jedla = array(8);
$ceny = array(8);
$index = array(8);
$polievky = array(2);
$polievkyCeny = array(2);
$polievkyIndex = array(2);
$i = 0;
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
if($i == 0){
array_push($jedla, $row['Jedlo']);
array_push($ceny, $row['Cena']);
array_push($index, $row['IndexJedlo']);
}else{
array_push($polievky, $row['polievka']);
array_push($polievkyCeny, $row['cena']);
array_push($polievkyIndex, $row['index']);
}
}
$result->free();
}
if ($mysqli->more_results()) {
$i = $i + 1;
}
} while ($mysqli->next_result());
}
$mysqli->close();

MYSQLI multi query function

I want to create a function that automatically makes a connection to the database and performs the given queries but I can't get it to work and it gives no errors.
I think I'm not outputting in the correct way my goal is to output a array that stores all the returned values from the queries.
Here is my code so far hope you can help:
public function db_query() {
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/app.ini');
$mysqli = new mysqli($ini['db_location'], $ini['db_user'], $ini['db_password'], $ini['db_name']);
// create string of queries separated by ;
$query = "SELECT name FROM mailbox;";
$query .= "SELECT port FROM mailbox";
// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);
if ($result) {
do {
// grab the result of the next query
if (($result = mysqli_store_result($mysqli, 0)) === false && mysqli_error($mysqli) != '') {
echo "Query failed: " . mysqli_error($mysqli);
while ($row = $result->fetch_row()) {
echo $row[0];
}
}
} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
echo "First query failed..." . mysqli_error($mysqli);
}
}
Note: I did not add the parameter for the query just for testing
purposes.
public function db_query($mysqli) {
$return = [];
$result = mysqli_query($mysqli, "SELECT name FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
$result = mysqli_query($mysqli, "SELECT port FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
return $return;
}
simple, clean, efficient, always works

how to query max value in column with php sqlite3?

I am not able to get max value from SQLite with PHP but getting 0 (zero) but If I run the query in SQLite I am getting COrrect value. The code is shown below.
class MyDB extends SQLite3 {
function __construct() {
$this->open('data.db');
}
}
$con = new MyDB();
$sql = "SELECT MAX(sd_id) FROM stu_data ORDER BY sd_id DESC LIMIT 1";
$result = $con->query($sql);
if ($result) {
if($row = $result->fetchArray(PDO::FETCH_ASSOC)) {
$lclId = $row[0]["MAX(sd_id)"] + 1;
$lclNo = $lclId;
}
} else {
$lclNo = '1';
}
Here I am Getting $row[0]["sd_id"] AS zero (0) always.
Your return value is not called sd_id as you have not aliased the value. You can either use
$row['MAX(sd_id)']
or better yet supply a column alias in the query:
SELECT MAX(sd_id) AS max_sd_id FROM stu_data
Then you can refer to it as $row['max_sd_id']. e.g.
$sql = "SELECT MAX(sd_id) AS max_sd_id FROM stu_data ORDER BY sd_id DESC LIMIT 1";
$result = $con->query($sql);
if ($result) {
if($row = $result->fetchArray(PDO::FETCH_ASSOC)) {
$lclId = $row['max_sd_id'] + 1;
$lclNo = $lclId;
}
} else {
$lclNo = '1';
}
Note that the ORDER BY sd_id DESC LIMIT 1 in your query is meaningless as it will only return 1 value anyway.
class MyDB extends SQLite3 {
function __construct() {
$this->open('data.db');
}
}
$con = new MyDB();
$sql = "SELECT MAX(sd_id) FROM stu_data ORDER BY sd_id DESC LIMIT 1";
$result = $con->query($sql);
if ($result) {
if($row = $result->fetchArray(SQLITE3_ASSOC)) {
$lclId = $row[0]["MAX(sd_id)"] + 1;
$lclNo = $lclId;
}
} else {
$lclNo = '1';
}
The Difference is Need to use fetchArray(SQLITE3_ASSOC) Instead of fetchArray(PDO::FETCH_ASSOC)

review system with function in variable

so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.

MySql/PHP Query Returning Empty

Here is my code:
$result = mysqli_query($dbconnection, Data::followUser($user_id, $followUser_id));
$result returns empty here.
followUser method in class Data
public static function followUser($user_id, $followUser_id) {
global $database;
$query = "
SELECT *
FROM profile_follow
WHERE user_id = '{$user_id}'
AND follow_id = '{$followUser_id}';";
$result = $database -> query($query);
$num = mysqli_num_rows($result);
if ($num < 1) {
$toast = "Follow";
$query = "
INSERT INTO profile_follow (user_id, follow_id)
VALUES ('{$user_id}', '{$followUser_id}');";
$result = $database -> query($query);
} elseif ($num > 0) {
$toast = "Unfollow";
$query = "
DELETE FROM profile_follow
WHERE user_id = '{$user_id}'
AND follow_id = '{$followUser_id}';";
$result = $database -> query($query);
}
return $toast;
}
I have verified the function works correctly in echoing out $toast. It is either Follow or Unfollow based on condition. I don't think I am handling it right when it comes out?
Supplemental:
Here is what I am doing with $result:
if ($result == "Follow") {
$output["result"] = "Follow";
echo json_encode($output);
} elseif ($result == "Unfollow") {
$output["result"] = "Unfollow";
echo json_encode($output);
}
What does this all accomplish? You've basically got:
mysqli_query($dbconnection, 'Unfollow');
which is NOT a valid query in any way. $result is NOT empty. It's a boolean false, indicating a failed query...

Categories