Serialize multiple data from database of same column - php

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

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

Why is this function only returning one (1st) value in what should be an array of 5?

I am running an SQL query when my user logs into my app to retrieve a list of 'communities' they are part of.
I am trying to test what values are being returned by pasting the login link directly into my address bar.
It should return an array of 5 entries, but it is only returning 1.
I have tested the SQL query in phpMyAdmin and it returns the correct result.
What am I doing wrong?
This is from userLogin.php
$communities = array();
$communities = $dao->getCommunities($email);
echo json_encode($communities);
Which runs the following function in MySQLDao.php
public function getCommunities($email){
$returnValue = array();
$sql = "SELECT communities.name \n"
. "FROM users \n"
. "join community_players \n"
. "on community_players.player_id=users.id \n"
. "join communities \n"
. "on communities.id=community_players.community_id \n"
. "WHERE users.user_email = '".$email."'";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue = $row;
}
}
return $returnValue;
}
This is currently returning {"name":"EnclliffeT"} in the browser.
However, there should be another 4 entries.
Your code is fetching only the first row. Replace these lines:
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue = $row;
}
}
with these:
if($result != null && (mysqli_num_rows($result) >= 1)){
while($row = $result -> fetch_array(MYSQLI_ASSOC)){
if(!empty($row)){
$returnValue[] = $row;
}
}
}
Your public function getCommunities($email){ is fetching only the first row, no matter how many are returned by the SQL query.
Try to apply the following change:
$results = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
$results[] = $row;
}
return $results;
A query produces a resultset. That resultset can contain 0 to n rows. Therefore you must unload the resultset row by row in a loop of some sort. A while loop is the best way of doing this.
public function getCommunities($email){
// the query
$result = $this->conn->query($sql);
if ( ! $result ) {
//report error somehow
exit;
}
$returnValue = array();
while ( $row = $result -> fetch_array(MYSQLI_ASSOC)){
$returnValue[] = $row;
}
return $returnValue;
}

Why is fetch_assoc() not returning a value?

For the life of me I can't figure out why fetch_assoc() is returning false here:
$username = $_POST['username'];
print("Username is " . $username . "<br>");
//Create query
$query = ("SELECT * FROM users WHERE username = '" . $username . "'");
print($query . "<br>");
//Run query
if (!$result = $db2 -> query($query)) {
print("Query failed!");
}
if (!$user = new LG_User($result))
print("Failed to create user!<br>");
while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
var_dump($rows);
print("User is " . $user -> first_name . "<br>");
The query is successful and the new user object is created, because the last line of code is printing $user->first_name correctly. I'm using the very same block of code to populate the $rows array on another page and it is working. What am I doing wrong here? If I try to use
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
instead of
while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
it still doesn't work. What am I missing here?
You haven't shown the code for the LG_User constructor, but if it's filling in $user from the database, it must be calling a fetch function itself. So when it returns, all the rows of the result have been fetched, and there's nothing left for your loop to read.
You can go back to the beginning of the result set with the data_seek method.
if (!$user = new LG_User($result))
print("Failed to create user!<br>");
$result->data_seek(0);
while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
var_dump($rows);

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

MYSQL Results; no records found statement [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Display Data From MYSQL; SQL statement error
I have the code below displaying data from a MYSQL database (currently looking into sql injection issue) I need to insert an error message when no results are found...not sure where to position this! I have tried the code if( mysql_num_rows($result) == 0) {
echo "No row found!" but keep on gettin syntax errors, does anyone know the correct position in the code for this?
--
require 'defaults.php';
require 'database.php';
/* get properties from database */
$property = $_GET['bedrooms'] ;
$sleeps_min = $_GET['sleeps_min'] ;
$availability = $_GET['availability'] ;
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
$result = do_query("SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'", $db_connection);
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
I have found few errors in your code that in line
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
You use bedrooms = '{$bedrooms}' but $bedrooms is not variable in whole cod it must be $preopery. I have made a few changes in your code given below please try it.
<?php
require 'defaults.php';
require 'database.php';
/* get properties from database */
/*if get $_GET['bedrooms'] value else ''*/
if (isset($_GET['bedrooms'])) {
$property = $_GET['bedrooms'];
} else {
$property = '';
}
/*if get $_GET['sleeps_min'] value else ''*/
if (isset($_GET['sleeps_min'])) {
$sleeps_min = $_GET['sleeps_min'];
} else {
$sleeps_min = '';
}
/*if get $_GET['availability'] value else ''*/
if (isset($_GET['availability'])) {
$availability = $_GET['availability'];
} else {
$availability = '';
}
$query = "SELECT * FROM `properties` WHERE bedrooms = '" . $property . "' AND sleeps_min = '" . $sleeps_min . "' AND availability = '" . $availability . "'";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
}
?>
Do var_dump($GET_) to debug whether you are getting valid strings. If any of these are blank, the query will try to match blank values instead of NULL. You should prevent this by doing:
if(!$_GET['bedrooms'] || $_GET['bedrooms'] == ''){
$property = 'NULL';
}//repeat for all three
$query = "SELECT * FROM `properties` WHERE 'bedrooms' = '$bedrooms' AND 'sleeps_min' = '$sleeps_min' AND 'availability' = '$availability'";
Instead of:
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
You can simply do:
$r = mysql_fetch_array($query);
But enclose that in a conditional to see if your query found anything:
if(mysql_affected_rows() > 0){
//your code here will execute when there is at least one result
$r = mysql_fetch_array($query);
}
else{//There was either nothing or an error
if(mysql_affected_rows() == 0){
//There were 0 results
}
if(mysql_affected_rows() == -1) {
//This executes when there is an error
print mysql_error(); //not recommended except to debug
}
}

Categories