Why does this simple mysql_query/SELECT/echo get "Array" as output? - php

I have written the code below, which should check the session variable against the database and give me the username which = user id which is in the session.
If I echo $session_name; I get a user id e.g. 30
If I echo $row2; I get Array
What am I doing wrong?
<?php
connect();
$session_name = $_SESSION[id];
$sql2 = "SELECT username FROM members WHERE member_id = '$session_name'";
$result2=mysql_query($sql2);
$row2 = mysql_fetch_array($result2);
echo $row2;
?>

try
echo $row2[0];
or even
print_r($row2);
to see what you are getting from db.

Try echoing $row2[0]. mysql_fetch_array returns one result row as an indexed array, which in this case has only one element/column. Also don't forget to test if $row2 === FALSE, which indicates that there were no results for the query.

<?php
connect();
$session_name = $_SESSION[id];
$sql2 = "SELECT username FROM members WHERE member_id = '$session_name' LIMIT 1";
$result2=mysql_query($sql2);
while($row2 = mysql_fetch_assoc($result2))
echo $row2['username'];
?>

The result of a fetch is always an array. In this case it's a one-dimensional array. Use $row2[0] (assuming your fetchmode is an array).
If your fetchmode is associative or object, it'd be $row2['username'].
Check here for more good info: http://php.net/manual/en/function.mysql-fetch-array.php

$row2 is in fact an array that represents the entire row returned. Try $row2[0], I think that will give you what you expected (the single field in the returned row).

That's because $row2 is an array. You used mysql_fetch_array to obtain it, and it returns an array, as the name of the function implies.
The array returned by mysql_fetch_array uses the column names from your SQL query as the keys. Thus
echo $row2['username'];
will return the data you expect.
As a sidenote: SELECT is technically a SQL clause, not a PHP function.

Related

Return result of an mysql function

I have installed this Levenshtein function in MYSQL. The maker advises to use this:
select levenshtein('butt', 'but') from test;
select levenshtein_ratio('butt', 'but') from test;
I want to calculate the Levenshtein Ratio between $search and each "name" entry in the DB and then echo it in PHP.
How can I accomplish that? Thanks in advance
$search = "Paul"; // The string I want compared to each DB entry
$query = "SELECT name, ??? FROM names"; // What's the MYSQL I need to use?
$response = #mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($response)){
echo "Levenshtein Ratio: ".$row['???'];
echo "<br>";
}
You need to use an alias the function return
SELECT levenshtein('butt', 'but') as levenshtein FROM
then it can be accessed from the levenshtein index.
$row['levenshtein']
Also note:
In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
So if you didn't want the alias you could do:
$row[1]
this is less readable/maintainable to me though.
When in doubt about what an array contains you can check it with print_r or var_dump. Those will give you the indices and the values the array has.
How about this ?
<?php
$search = "Paul"; // The string I want compared to each DB entry
$query = "SELECT name, levenshtein(name, '".mysqli_real_escape_string ($dbc, $search)."') AS result FROM names";
$result = #mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
echo "Levenshtein Ratio for ".$row['name'].' : '.$row['result']."<br />";
}

How do I return data when doing specific MySQL query using PHP?

Here is my PHP MySQL query:
$query = "SELECT falsegoto FROM timeconditions WHERE [timeconditions_id] = 0";
$result = mysql_query($query);
There should be only a single result from this query, and I'm not sure how display it in PHP?
mysql_result() seems to only work with larger data sets?
Any help or explanation would be valued.
As Peeha mentiod, your using mysql, but it's better to use mysqli
So the code will then look like this:
$query = "SELECT falsegoto FROM timeconditions WHERE [timeconditions_id] = 0";
$result = mysqli_query($query);
while($row = myslqi_fetch_assoc($result){
// DO STUFF
}
I use this for everything. It just loops through every row in the result. and if there's just one row, it while's only one time....
use it like this :
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
You have to fetch the row, there are a few methods of doing it: mysql_fetch_object, mysql_fetch_row, mysql_fetch_array and mysql_fetch_assoc.
These methods will read a single line from the result and remove it from the handler, so if you loop the call it will read all the rows, one by one until it reaches the end and returns false.
example:
while($obj = mysql_fetch_object($result)){
echo $obj->name;
}
PHP.net documentation:
mysql_fetch_object,
mysql_fetch_row,
mysql_fetch_array,
mysql_fetch_assoc

Array Rand Not Working with MySQL Fetch Array

I wrote a PHP script that retrieves values from a MySQL Query. I used mysql_fetch_array to add the results to an array. I am trying to select a random value from the array, however array_rand doesn't seem to work. My code is below:
<?php
session_start();
ob_start();
require_once 'includes/db_connection.php';
require_once 'includes/contest.php';
require_once 'includes/survey.php';
require_once 'includes/poll.php';
require_once 'includes/clients.php';
require_once 'includes/user.php';
//Select All Entries from Contest and Save as Array
//Select
mysql_connect(localhost,s2ktest_s2kuser, Bc33iyZYQWgUmguBehPI);
$dbname = 's2ktest_s2k';
mysql_select_db($dbname);
$contestid = 20;
$query = "SELECT UserID FROM Contest_Entered WHERE ContestID = $contestid";
//Save Result
$result = mysql_query($query) or die(mysql_error());
//Save All Contest Entries in Array
$entries = mysql_fetch_array($result) or die(mysql_error());
//Output all Rows
//While Each Entry in the Array is a Value
while($entries = mysql_fetch_array($result))
{
echo $entries;
echo "</br>";
}
echo array_rand($entries);
//mysql_free_result($result);
?>
Maybe because you don't have any array...
The while is only generating one row at the time.
while($entries = mysql_fetch_array($result))
{
echo $entries;
$arr[] = $entries;
echo "</br>";
}
echo array_rand($arr);
mysql_fetch_array() retrieves only one row at a time. First, load the whole result set into an array using the [] append syntax, then fetch randomly from that.
$all_entries = array();
// Using MYSQL_NUM to retrieve only numeric keys
// by default, mysql_fetch_array() gets both numeric and associative keys
while($entries = mysql_fetch_array($result, MYSQL_NUM))
{
// Append all rows onto an array, only a sinlge value so you get a 1D array
$all_entries[] = $entries[0];
}
// Then call array_rand() against $all_entries
echo array_rand($all_entries);
Disclaimer:
Start thinking about migrating away from the old mysql_*() functions to a modern API supporting prepared statements. PDO is excellent and portable between RDBMS, while MySQLi is a good alternative as well.
That's because you're changing the value of $entries from an array to a string when you start the loop. Try echoing array_rand($entries) before the loop instead.
However, if you are instead trying to retrieve a random row from a table (rather than a random column from a row, as your code appears to do) use ORDER BY RAND() in your query. It's unclear what you're going for.
Good luck!

Selecting one row from MySQL using mysql_* API

I have the following query:
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
print_r ($row);
and the output I am getting is:
Resource id #2
Ultimately, I want to be able to echo out a single field like so:
$row['option_value']
Without having to use a while loop, as since I am only trying to get one field I do not see the point.
I have tried using mysql_result with no luck either.
Where am I going wrong?
Try with mysql_fetch_assoc .It will returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. Furthermore, you have to add LIMIT 1 if you really expect single row.
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];
Functions mysql_ are not supported any longer and have been removed in PHP 7. You must use mysqli_ instead. However it's not recommended method now. You should consider PDO with better security solutions.
$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];
use mysql_fetch_assoc to fetch the result at an associated array instead of mysql_fetch_array which returns a numeric indexed array.
Though mysql_fetch_array will output numbers, its used to handle a large chunk.
To echo the content of the row, use
echo $row['option_value'];
Try this one if you want to pick only one option value.
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
echo $row['option_value'];
What you should get as output with this code is:
Array ()
... this is exactly how you get just one row, you don't need a while loop. Are you sure you're printing the right variable?
Ultimately, I want to be able to echo out a signle field like so:
$row['option_value']
So why don't you? It should work.
It is working for me..
$show = mysql_query("SELECT data FROM wp_10_options WHERE
option_name='homepage' limit 1"); $row = mysql_fetch_assoc($show);
echo $row['data'];
is this is a WordPress?
You shouldn't do it like you've done!
To get option from DB use get_option!
this shoude work
<?php
require_once('connection.php');
//fetch table rows from mysql db
$sql = "select id,fname,lname,sms,phone from data";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
for ($i = 0; $i < 1; $i++) {
$row =mysqli_fetch_assoc($result);
} $emparray[] = $row;
echo $emparray ;
mysqli_close($connection);
?>
make sure your ftp transfers are in binary mode.

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories