Kohana : Unable to Display $query on the webpage [duplicate] - php

I'm trying to select a value from a database and display it to the user using SELECT. However I keep getting this error:
Notice: Array to string conversion in (pathname) on line 36.
I thought that the #mysql_fetch_assoc(); would fix this but I still get the notice. This is the part of the code where I'm getting the error:
{
$loggedin = 1;
$get = #mysql_query("SELECT money FROM players WHERE username =
'$_SESSION[username]'");
$money = #mysql_fetch_assoc($get);
echo '<p id= "status">'.$_SESSION['username'].'<br>
Money: '.$money.'.
</p>';
}
What am I doing wrong? I'm pretty new to PHP.

The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:
'.... Money:'.$money['money']

Even simpler:
$get = #mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");
note the quotes around username in the $_SESSION reference.

One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.

Store the Value of $_SESSION['username'] into a variable such as $username
$username=$_SESSION['username'];
$get = #mysql_query("SELECT money FROM players WHERE username =
'$username'");
it should work!

mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].

You cannot echo an array.
Must use print_r instead.
<?php
$result = $conn->query("Select * from tbl");
$row = $result->fetch_assoc();
print_r ($row);
?>

Related

php array to string conversion odbc_exec count

i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.
$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;
i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error
Array to string conversion in /var/www/html/xxx.php on line 85
Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!
Problem is:-
You are trying to echo a result-set object of array type.
Solution (check the code comments):-
$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count
$result2 = odbc_exec($connect,$query2); //prepare and execute query
while (odbc_fetch_row($result2)) { //iterate over result-set object
echo odbc_result($result, "MYCOUNT"), "\n"; // echo count
}
What is happening here is you are echoing an array object type that is also a resource type and php echo only string and other primitive type variables.
so you need to use a loop to access the row or to get row count and access row just use a foreach($results as $result)
to get row count visit this sqlsrv-num-rows . on this official php link you can get more example how to fetch data.

pdo array how fetch all info from database

I need to fetch all the info from a query , so I can use it for other purposes, the issue is that I'm just getting 1 result of each kind and I need them all, here is my script:
<?php
require_once 'init.php';
$base_datos = DB::getInstance();
$base_datos->query ("SELECT lname, fname, category,user_id, SUM(points) as Point, SUM(amount)as Amount FROM request GROUP BY user_id");
$get_info = $base_datos->results();
$real_info = $get_info[0];
$name = $real_info->lname;
$last_name = $real_info->fname;
$categories = $real_info->category;
echo "$name";
///var_dump ($get_info);
?>
when echo $name all i get is one name i need to get them all and so on with the other value, when i do var_dump i got all i need, but i need to loop through,I'd searched all around and was not lucky.
this is what I'm trying to output on php page
I'm assuming $get_info is an array of objects based on how your code is currently written. Right now you're setting the first record of $get_info to $real_info.
So to access all of the records loop through $get_info like this.
foreach($get_info as $real_info) {
echo $real_info->fname.' '.$real_info->lname;
}

$result only one row then convert into session

i am trying to query one single row from a table 'account'. I kind mess up with the MYSQLI so i need some advice. How can i do that?
$link = mysqli_connect("localhost","root","","database") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM account WHERE username='".$user."' AND password='".$passcode."' LIMIT 1";
$result = $link->query($query) or die("Error " . mysqli_error($link));
$numrow = $result->num_rows;
$res = $result->fetch_assoc();
After the query i want to copy the data to a session, i am doing like that:
session_start();
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
And after these, how can i print the data?
$tableau = $_SESSION['tableau'];
echo "$tableau['username']";
From your question:
how can i print the data?
First of all you need to add error_reporting() on in your code:
error_reporting(E_ALL);
You are saving values in an array for $_SESSION:
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
If you look your session array it's not an associative array.
So you can not get the result like:
$tableau = $_SESSION['tableau'];
echo $tableau['username'];
Solution:
You can get username from session array as:
echo $tableau[1]; // username on second index.
Solution 2:
If you want associative index than you need to use associative array as:
$tableau = array(
"cod_acc"=>$res['cod_acc'],
"username"=>$res['username']);
$_SESSION['tableau'] = $tableau;
Now you can use as you need. Note that I am removing password field from session I think its not need.
Side note:
I don't know why are mixing Procedural and Objected Oriented style together.
The problem was in some other line code, sorry for the post. But thanks guys.

Formatting array output using foreach function

I have a script that follows that is supposed to collect data from a field"UserID" in my sql table, submit all data into an array, and then compare a variable to whats in the array. If the value of the variable is already in the array, tell the user that that value is invalid.
$sql = "SELECT *" //User info
. " FROM Users" ;
$result = mysql_query($sql);
//insert where line for assessorid
$users = array();
while(($user = mysql_fetch_assoc($result))) {
$users[] = $user;
}
foreach($users as $user){
$user['UserID'];
}
I need the output of $users to be equivalent to array('user1','user2','user3');
Whats happening is data comes in from a form as $user_name. I want to use this in a statement like follows:
if(in_array($user_name,$users)){
echo "username available"
}
else{
echo "not available"}
I tried using the extract function, but that just created a big mess.
Im not sure what is incorrect about what I'm doing, unless the format of $users as an array cannot be parsed in the in_array() function as it is formatted currently. Any advice is much appreciated. Thanks!
$sql = "SELECT USERID FROM Users" ;
$result = mysql_query($sql);
$users = array();
while(($user = mysql_fetch_assoc($result))) {
$users[] = $user['USERID'];
}
When you are saying
$users[] = $user;
You are not specifying which column in the result set to be appended to the array.
Maybe I am missing something... Why not do it like this:
SELECT UserID FROM Users WHERE Username = 'username'
Then just use mysql_num_rows() to check if the username already exists or not. This should be both faster and more efficient (memory-wise).
In that case, you collect all data from the database and need to do some inefficient processing in PHP as well. It is better to query for that value to see if it is in the database, so:
$username = mysql_real_escape_string($username);
$query = "
select
count('x') as usercount
from
users u
where
u.username = '$username'";
The, if the 'usercount' is 0, the username does not exist. If > 0, the username does exist. This way, you let the database do the work it is designed to do, and the only value that is actually retreived is that single number.
Have you tried modifying your query? Currently you are getting all of the values for every user, but you just seen to need UserID. You could do this:
$sql = "SELECT UserID FROM Users";
$result = mysql_query($sql);
$users = array();
while(($user = mysql_fetch_assoc($result)))
{
$users[] = $user['UserID'];
}
// ...
if (in_array($user_name, $users))
{
echo 'Username not available';
}
else
{
echo 'Username available';
}
Or you could just look up in the database for the given username:
$sql = 'SELECT count(*) FROM Users WHERE UserID = '.mysql_escape_string($user_name);
$result = mysql_query($sql);
// and then just check if the resulting row is equal to 0
Are you attempting to write a script that will check if a username is taken?
If so, it may be easier (and more efficient) to structure the actual query towards this end rather than relying on the programmatic approach.
$sql = "SELECT COUNT(*) FROM Users WHERE Username = '$username'";
Then you could apply this result to a count and allow the user to register or not based on whether a value greater than zero (a user has already taken that name) or not (its free) is returned.
As has been mentioned, that is a rather inefficient way to check for an existing username. The suggestions for modifying your query are good advice.
However, to address the problem with the code you provided:
in_array() will not detect the presence of a value in a multi-dimensional array. Your $users array probably looks something like this:
$users = array(
array('userID', 'foo', 'bar'),
array('userID', 'foo', 'bar'),
array('userID', 'foo', 'bar')
)
and in_array will not search below the first set of indexes. If this is really what you want to do, see this question: in_array() and multidimensional array

How do i parse the the value from a string in the function call?

i have function which is something like this
function multiple_delete($entity1,$entity2,$entity2) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $entity1;
echo $entity2;
echo $entity3;
}
and my function call is
multiple_delete('$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
keeping in mind the three value which i am passing through the parameter is the entity name of particular table.
now this function will print it as the string i.e ($row['pic_title'], $row['pic_brief']', $row['pic_detail']) and hence not parse it as the value which i want it to do. if it parse it as the value then i will be able to get the records from the database. i have tried with the combination of single quotes, doubles, with concatenation operator etc. is there any way i tell the script that do not parse it as the string instead treat it as it have been declared to fetch the value from database. does php have any function for this ? or i am going wrong with the logic.
if i skip the parameters and declare in the functions something like this.
echo $row['pic_title'];
echo $row['pic_brief'];
echo $row['pic_detail'];
it works perfectly fine . why is that when i try to achieve the same thing with the help of parameter it refuses to fetch the value from the database, and instead it returns the same declared string from the function call.
Please do not tell me that i dont need that parameter, i need it because i want it to perform the dynamic data manipulation, with regard to different tables and different table entities. and the above function is just the demonstration of my problem not the exact function. if you want to have a look at the exact function you can check here.
What is wrong with my function?
thank you
Just pass the names of the columns:
multiple_delete('pic_title', 'pic_brief', 'pic_detail');
Then you can use them to access the corresponding values in the row array by using the names them as keys:
function multiple_delete($entity1, $entity2, $entity3) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[$entity1];
echo $row[$entity2];
echo $row[$entity3];
}

Categories