Having issue using shuffle with array and mysql query [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I' am running into a problem where an array is not being able to shuffle. I want the array to randomized for each page loads. I followed the documentation but something still wrong over here
Error Message
Warning: Invalid argument supplied for foreach() in E:\xampp\htdocs\projects\snppets\sidebar.php on line 65
This is the code that gets the friends list, makes the sting into array, counts the array and shuffles it.
$friends = get_friends_IDS($profile_id);
$friends = make_string_to_ARRAY($friends);
$friends_count = count($friends);
$friends = shuffle($friends);
This is the code that is in line 65
<?php
foreach($friends as $id){
$sql = "SELECT profile_id, profile_photo, profile_username, profile_name FROM profile WHERE profile_id='$id' LIMIT 1";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT();
if($db->NUM_ROWS() > 0){
foreach($rows as $row){
$friends_profile_id = $row->profile_id;
$friends_profile_photo = $row->profile_photo;
$friends_profile_username = $row->profile_username;
$friends_profile_name = $row->profile_name;
}
}
}
?>
This function gets the friends list from the database
function get_friends_IDS($profile_id){
global $db;
$sql = "SELECT profile_id, profile_friends FROM profile WHERE profile_id='$profile_id' LIMIT 1";
$query = $db->SELECT($sql);
if($db->NUM_ROWS()){
foreach($db->FETCH_OBJECT() as $row){
return $row->profile_friends;
}
}
}
This is the function makes a string into array
function make_string_to_ARRAY($array){
$array = explode(',', $array);
return $array;
}
When I remove the shuffle then it works fine...

shuffle() returns boolean value.
So $friends = shuffle($friends); makes $friends as a boolean variable.
just use shuffle($friends); to shuffle it

Related

How do I get my code to echo only once instead of twice? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
My code echo's Hey or Hello twice once the requirements are met.
This is supposed to check whether or not a person has something uploaded, depending on if they do or don't either message displays.
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$sqlImg = "SELECT * FROM users WHERE idUsers='$current'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
if ($rowImg['profile_img'] == 0) {
echo "hey";
} else {
echo "Hello";
}
}
}
}
I expect the output to echo either word once, but the actual output is echoing it twice.
You don't need two loops. The outer loop is running for every user in the table, regardless of whether they match $current. For each of them you're doing another query that just gets the $current user, and echoing their status.
If idUsers is a unique key, you don't even need any loops. Just do one query and fetch the row.
You should also use a prepared statement to prevent SQL injection.
$stmt = $conn->prepare("SELECT profile_img FROM users WHERE idUsers = ?");
$stmt->bind_param("s", $current);
$stmt->execute();
$result = $stmt->get_result();
$rowImg = $result->fetch_assoc();
if ($rowImg['profile_img'] == 0) {
echo "hey";
} else {
echo "Hello";
}

Warning: Illegal string offset [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I new to oop and I have a image displaying when I had a single a array query (requesting the image url only) but when I added a second dimension to the query array (image id in the table) I just ended up getting a warning message 'Warning: Illegal string offset'. I have used mysqli_fetch_assoc in the database class and then running the result through a foreach loop.
This is the message I am getting.
Thanks in advance for any help given.
page code
$user = $_SESSION['user_name'];
$query = "SELECT gallery_image, 'gallery_id' FROM gallery WHERE user_name = '$user' ORDER BY gallery_id DESC";
$result = $obj_db->get_gallery($query);
foreach ($result as $image ) {
foreach ($image as $key => $value) {
echo '<div class="gallery_item"><img src="'.$value['gallery_image'].'"></div>';
}
}
Database class code
function get_gallery($sql){
$obj_res = mysqli_query($this->obj_db_conn, $sql);
if(mysqli_errno($this->obj_db_conn)){
die ("Failed query: $strSql".$this->obj_db_conn->error);
}
$arResults = array();
while($arRow = mysqli_fetch_assoc($obj_res)){
$arResults[] = $arRow;
}
return $arResults;
If your var_dump output on $result give this,
array(2) {
[0]=> array(2) {
["gallery_image"]=> ""
["gallery_id"]=> ""
}
[1]=> array(2) {
["gallery_image"]=> ""
["gallery_id"]=> ""
}
}
you don't need two nested foreach loops in your page code. The one foreach loop could be enough.
$query = "SELECT gallery_image, gallery_id FROM gallery WHERE user_name = '$user' ORDER BY gallery_id DESC";
$result = $obj_db->get_gallery($query);
foreach ($result as $image ) {
echo '<div class="gallery_item"><img src="'.$image['gallery_image'].'"></div>';
}

codeigniter where = does not work with words [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The following code is not working properly:
$query = $this->db->query("SELECT accountType FROM users WHERE id = $loggedID" );
It errors if the $loggedID is words like "justin", but if its only number like 201110523, it works. I don't know what is wrong. The datatype of the id in users is varchar.
public function account_type_student(){
$loggedID = $this->input->post('id');
$query = $this->db->query("SELECT accountType FROM users WHERE id = $loggedID" );
foreach ($query->result() as $row)
{
$query = $row->accountType;
}
if($query=="student"){
return true;
}
else{
return false;
}
}
When it is a word / string like "justin" then you have to escape your variable:
$query = $this->db->query("SELECT accountType FROM users WHERE id = '$loggedID' " );
Or use the active pattern syntax:
$this->db->select('accountType');
$this->db->where('id', $loggedID);
$query = $this->db->get('users');

PHP MySQL query not working using my DB class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've set up a Database class, a User class and a UserTools class to interact with a MySQL database. It seems that my UPDATE, DELETE and INSERT commands are working find but I can't figure out what's going on with my SELECT statements. I'm only using mysql right not until I get everything working as I'd like, then I'll switch over to mysqli or PDO. But anyway, here's what I'm looking at....
DB class....
public function select($table, $where) {
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
return $this->processRowSet($result, true);
return $this->processRowSet($result);
}
public function processsRowSet($rowSet, $singleRow=false) {
$resultArray = array();
while ($row = mysql_fetch_assoc($rowSet)) {
array_push($resultArray, $row);
}
if ($single_row === true)
return $resultArray[0];
return $resultArray;
}
UserTools class
public function getUser($id) {
$db = new DB();
$result = $db->select('users', 'id = $id');
return new User($result);
}
There seems to be an issue with how I'm processing the rows or something. I've followed similar setups with UPDATE,DELETE,INSERT and they seem to work fine but I don't know whats going on here.
If I call an instance of new UserTools(), then try to run the getUser() function, it's not returning anything the way it's set up. If I keep the result from being pushed through the User class constructor, it just returns a Reference Value, meaning that I'm not processing the rows properly.
I have a feeling I'm overlooking something stupid here so any help would be greatly appreciated. Thanks!
For a start,
$result = $db->select('users', 'id = $id');
Should be
$result = $db->select('users', 'id = '.$id);
As Casimir mentioned, there's a typo in public function processsRowSet
I'd echo $sql; die; to check if the query is complete.
In UserTools class: 'id = $id' wouldn't parse in $id. Instead do "id = {$id}" or similar so that it can parse $id.

Output value from array (php, mysql) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
function getById($id) {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `ids` WHERE `id` = '".$mysqli->real_escape_string($id)."'") or die($mysqli->error);
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
How do I get the value of id field?
$data = getById(1);
echo $data[0] or echo $data['id'] doesn't work.
Your function returns an array of arrays, so to get the first ID:
$data = getById(1);
echo $data[0]['id'];
Side notes:
Globals are undesirable. Consider passing the database connection object to the function as an argument instead.
Escaping like that is a primitive way of preventing SQL Injection. The use of a Prepared Statement would be more secure and easier.
or die(....) is bad practice because it exposes the detailed MySQL error to users, and it's hard to remove if you have written that hundreds of times. An alternative is trigger_error() which silently writes to your error log.
You no need to use while and array. Get single row and you can get without using array:
function getById($id) {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `ids` WHERE `id` = '".$mysqli->real_escape_string($id)."'") or die($mysqli->error);
return $result->fetch_array(MYSQLI_ASSOC);
}
$data = getById(1);
echo $data['id'];

Categories