MySql/PHP Query Returning Empty - php

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...

Related

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

Can't we call $result as variable in 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;
}

Get row from SQL with PHP

I am using the following method to query from my SQL database:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = (what goes here?)
I am trying to get the string name from users, how can I do this?
If your query is right then
try this:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = $result['result'][0]['name'];
You forgot to pass the value to the function
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1")
$name = "";
if(! isset($result["error"]) and isset($result["name"])) // check it returns error or not. then check name field exist or not.
{
$name = $result["name"];
}
echo $name;

function call inside a function in php not working

This code is a function calling a function in php. The function call is never called.
function saveSubject(){
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x])){
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}
function savePre($code, $y){
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM)){
$c = $row[0].$y;
if(isset($_POST[$c])){
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
Calling function savePre() in saveSubjec() but the calling is not working. I cannot find out what is wrong. Please help!
Simple...
You code is
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0)
{
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
from above code you can imagine that you are inserting record to database and then selecting that record using subcode match where condition so it will always return 1 as output so your else condition will never get execute.
That's the reason why you are not able to call savePre function.
You want to define savePre() function above the saveSubject() function. Use this.
function savePre($code, $y)
{
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM))
{
$c = $row[0].$y;
if(isset($_POST[$c]))
{
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
function saveSubject()
{
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x]))
{
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}
else
{
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}

Serialize multiple data from database of same column

I'm new to PHP and using serialized data,
I have a Database which has a 2 tables, user & character.
characterId has a relation with userId.
An user has 2 characters, so I wanted to get the data with the following code:
public static function getCharacter() {
$mysqli = Controller_Core_Config::getDB();
if ($mysqli != null) {
$user = unserialize($_SESSION['user']);
$sql = "SELECT * FROM `character` WHERE `userId`='" . $user->getId() . "'";
$result = $mysqli -> query($sql);
if ($result !== FALSE && $result -> num_rows > 0) {
$row = $result -> fetch_assoc();
$_SESSION["character"] = serialize(new Model_Game_User(
$row['characterId'],
$row['characterName'],
$row['userId'],
$row['level']
));
} else {
echo "You have no characters.";
}
}
}
And If I wanted to show the data I use the following code:
//some code
$character = unserialize($_SESSION["character"]);
$output .= $character->getCharacterName() . "<br>";
//some code
My problem is, that when I var_dump the ($_SESSION["character"])
I get only 1 character:
string(202) "O:15:"Model_Game_User":4:{s:28:"Model_Game_UsercharacterId";s:1:"3";s:30:"Model_Game_UsercharacterName";s:9:"adminious";s:23:"Model_Game_UseruserId";s:1:"2";s:22:"Model_Game_Userlevel";s:1:"3";}"
And my question is, is it possible to have multiple 'characters' in serialized data?
You are not looping over your results. You are just adding the first result found into the session
You would need something like this to replace you if block:
if ($result !== FALSE && $result -> num_rows > 0) {
$_SESSION["character"][] = array();
while($row = $result -> fetch_assoc()) {
$_SESSION["character"][] = serialize(new Model_Game_User(
$row['characterId'],
$row['characterName'],
$row['userId'],
$row['level']
));
}
}

Categories