Retrieve MySQL field using PHP - php

I need to get a field from a mySQL database using PHP
The problem is that in my mysql panel I use this sql code:
SELECT * FROM TESTS WHERE TEST_ID=1
and I get exactly what I want (I see the row that I want to display)
But if i use this code in PHP:
<?php
$con=mysql_connect("localhost", "root", "psw") or die("\nConnection Failed\n");
mysql_select_db("mydb")or die("\nDB Failed\n");
$query = "SELECT * FROM TESTS WHERE TEST_ID=1";
$result=mysql_query($query);
echo $result;
mysql_close($con);
?>
all I get is "Resource ID #3"
why??

the $result is a resource which is a link to a result set from mysql. To get the actual data you have to do something like:
$data = mysql_fetch_assoc($result);
print_r($data);
You would need to repeat the mysql_fetch_assoc() call for each row you want to retrieve, until it returns false, indicating there are no more rows, which can be done in a while loop like this:
while ($data = mysql_fetch_assoc($result)) {
print_r($data);
}

Watch out :
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.

you can use mysql_fetch_assoc
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo $row["userid"]; // sample column
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_fetch_assoc example

You have received a MySQL resource instead of the resultset you want. You've only received a pointer to the result.
You have to use functions like mysql_fetch_object, mysql_fetch_assoc, mysql_fetch_row etc to get the wanted resultset. Please check the manual here:
http://php.net/manual/en/book.mysql.php

Try to fetch result in any variable and print that It will work.
Like this :
<?php
$con=mysql_connect("localhost", "root", "psw") or die("\nConnection Failed\n");
mysql_select_db("mydb")or die("\nDB Failed\n");
$query = "SELECT * FROM TESTS WHERE TEST_ID=1";
$result=mysql_query($query);
$row = mysql_fetch_array($result)
print_r($row);
mysql_close($con);
?>
Hope this will help you... :)

Related

Passing mysql_query to JSON file does not work

I have a small code that should convert a query to my mysql database into a json file, but it does not return anything.
I have seen this example in many places but it does not work for me
Of course I checked before the query contains rows
I appreciate the help
<?php
if (!$enlace = mysql_connect('X.X.X.X', 'xxxx', 'xxxx') or !mysql_select_db('xxxx', $enlace)) {
echo 'No pudo conectarse a mysql';
exit;
}
$sql = 'SELECT * FROM `Tabla`';
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json[]=$row;
}
echo json_encode($json);
?>
The reason for not getting anything is because you are overwriting the array variable,
also note that you need to use mysqli since mysql_ is deprecated.
Change this line:
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json=$row;
}
to:
$resultado = mysqli_query($sql, $enlace);
$json = array();
while($row=mysqli_fetch_assoc($resultado)){
$json[]=$row;
}
Fist of all use mysqli instead of mysql it is deprecated since PHP 5.5.0.
And then add the row to the array instead of overwriting it.
$json[] = $row;
for test add this line in the loop
$json = [];
while($row = mysql_fetch_assoc($resultado)){
$json[] = $row;
print_r($row);
}
If you get no output the query is not giving you any results
You may try converting to array to be sure.
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
}
and yes simple debugging is important just use var_dump() to identify the issue
var_dump(['socket:', $resultado]); $i=0;
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
var_dump([$i++, $row]);
}
exit();
And of course you should not use deprecated functions but i assume this is a learning environment or just an old working system

PHP unable to print mysql_query() result

I have code
$email = "jb#tlb.com";
$row = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".$email."');");
echo $row[0];
However, nothing is echoed.
This is strange because something is being returned because, later in the code I have a function that is CALLED:
if ( $row[0] == 0 ) { echo "Email address is available<br>";};
However: this is strange because when i put the SAME CODE into mySQL database command prompt:
It clearly returns 1 or TRUE.
The mysql_query is returning 0 when the same exact command in mysql command prompt returns 1. Further: I am unable to echo the result for debugging purposes.
EDIT: Please not, the regular mySQL command is returning this and ONLY this:
EDIT: Here is there entire database:
MySQL query gives you a ressource. After that you have to fetch the data with mysql_fetch_assoc or mysql_fetch_row or something else for example. But its better to use prepared statements with mysqli or PDO to get more security.
$email = "jb#tlb.com";
$res = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".myql_real_escape_string($email)."')");
$row = mysql_fetch_assoc($res);
echo $row['email'];
Answer to your question:
$email = "jb#tlb.com";
$res = mysql_query("SELECT email FROM accounts WHERE email='".mysql_real_escape_string($email)."')");
$numRows = mysql_num_rows($res);
if($rowRows > 0) {
echo "Record Available";
}
You need to actually retrieve the result set from the query. mysql_query() just returns a resource handle for a successful select. You then need to fetch the results using mysql_fetch_* class of functions. Alternatively, you can use mysql_num_rows() to determine the number of rows returned in the result set.
In this case it is really senseless to wrap your actual query into a subquery. Just run your select and determine the number of rows:
$email = "jb#tlb.com";
$result = mysql_query("SELECT email FROM accounts WHERE email='".$email . "'");
if($result) {
$row_count = mysql_num_rows($result);
echo $row_count;
}
Also, you should not be writing new code using mysql_* functions, as these are deprecated. I would suggest mysqli or PDO extensions instead.
You need to do something like
while ($r = mysql_fetch_assoc($row))
{
echo $r[0];
}
after that code.
Let me know.

How do get all the data from a single table in mysql using php?

I'm trying to simply get all the data from a mysql table using the following code:
$dbc = mysqli_connect('host', 'user', 'password', 'table');
$q = 'SELECT * FROM users';
$r = mysqli_query($dbc, $q);
$user_array = array();
while ($row = mysql_fetch_array($r))
{
$user_array[]=$row;
}
echo "<br />";
echo "print r of user_array: <br />";
print_r($user_array);
i'm getting nothing. I looked at this tutorial (http://www.w3schools.com/php/php_mysql_select.asp), among others, but all they do is confuse me.
What am I doing wrong?
try changing this
mysql_fetch_array($r)
to
mysqli_fetch_array($r)
You have connected via the procedural MySQLi API (mysqli_connect()), but you are attempting to use the old mysql_fetch_array() from the old mysql_*() API. They aren't compatible.
You need to fetch via mysqli_fetch_array() or mysqli_fetch_assoc() instead. mysqli_fetch_assoc() is recommended unless you really need numeric keys in addition to column names in the output $row:
// Check for errors.
if ($r) {
while ($row = mysqli_fetch_assoc($r)) {
$user_array[] = $row;
}
}
else echo mysqli_error($dbc);
What you're working with now is a simple query with no parameters, just a SELECT * without a WHERE clause. For the future, when you start adding WHERE conditions, you'll want to start reading about prepared statements and mysqli::prepare().

Loading MySQL data into a PHP array

I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?
Code:
//Get active listing IDs
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());
if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};
Thanks,
Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.
while($row = mysql_fetch_array($active)) {
// Your code here
}
Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.
In PDO it's rather straight forward:
$rows = $conn->query($active)->fetchAll();
See PDO::queryDocs and PDOStatement::fetchAllDocs.
With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.
Code for mysqli
$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
$rows = $result->fetch_all();
}
with PDO it's nearly the same
$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
$rows = $result->fetchAll();
}

How can I echo an array of values from a php mySQL query?

Basically I am attempting to make a login. I understand a very small amount of php, but everytime I try to log in it works. So it is not following my if statement below. So I would like to see if anyone can help me print the $results as not a string. Everytime I echo it, it says error can not print as string. Which makes me think its an array, can someone help ? =(
<?php
include('include/dbConnection.php');
if (isset($_REQUEST['attempt']))
{
//variables
$user = $_POST['user'];
$password = sha1($_POST['password']);
//SQL statement
$query = "SELECT COUNT(user)
FROM users
WHERE user = '$user'
AND password = '$password'";
//Execute prepared MySQL statement
$results = mysqli_query($dbc,$query) or die('Error querying database');
/* Here is where I want to print $results
if ($results = 1)
{
session_start();
$_SESSION['$user'];
header('location: home.php');
}
else
{
echo $results + 'Incorrect Username or Password';
}
*/
//Close dbConnect
mysqli_close($dbc);
}
?>
Use var_dump($output) or print_r($output) to display contents of an array.
You have to use this:
echo "<pre>";
print_r($results);
echo "</pre>";
It first echoes so that the print of the array is formatted properly. If you don't do this it will all be on one line.
Hope this helped! :D
mysql_query() returns a statement result handle, NOT the data you've requested in the query. You first have to fetch a row of data to get access to the actual query data:
$result = mysqli_query(...);
$row = mysqli_fetch_row($result);
$count = $row[0];
mysqli_query function returns false for unsuccessful queries. it returns a MySQLi_Result object for select or show queries and true for insert and update queries.
if your query fails for some reason your script will die because of or die statement and never returns false.
if ($results = 1)
statement assigns 1 to your result variable. when your script runs, your code enters this if block. because you control the assignment statement whether it is done or not.
your query is a select, mysqli_query function returns MySQLi_Result object.

Categories