I am trying to Build a simple search that first grabbs 'query' from a form passed from a HTML form through the url to this script. Once I run the script I get the output: Resource id #140Resource id #141Resource id #142. Why am I getting this output and what does it mean?
Side note I am just using the "echo" as a way to see the output of each variable.
<?php
//connect to database
mysql_connect("localhost", "user", "password") or die("Error connecting to database: " .mysql_error());
mysql_select_db("dataBase") or die(mysql_error());
?>
<?php
$query = $_GET['query'];
// gets value sent over search form
$user_id = mysql_query("SELECT id FROM users WHERE email = '$query'") or die(mysql_error());
echo $user_id;
$account_id = mysql_query("SELECT 'account_id' FROM accounts_users WHERE 'user_id' LIKE ('$user_id')") or die(mysql_error());
echo $account_id;
$user_name = mysql_query("SELECT 'account_name' FROM accounts WHERE 'id' LIKE ('$account_id')") or die(mysql_error());
echo $user_name;
?>
This is not the way to print the results. The method mysql_query returns a resource that you have to use within a loop to actually print the results. For instance, loop at the second example in the official doc page.
P.S. $query = $_GET['query']; using this statement you could have Sql injections problems.
Try something similar to this - after first "SELECT" query :
while($user_id_obj = mysql_fetch_object($user_id))
{
echo $user_id_obj->id;
}
The way you implemented leads to SQL Injection Attacks
SQL Injection Attacks Example
This could be possible in two ways.Which is usefull for you is depends on your requirements.
1.if your query contains a single value as a result then following code with changes in your code will be usefull for you.
<?php
//connect to database
mysql_connect("localhost", "user", "password") or die("Error connecting to database: " .mysql_error());
mysql_select_db("dataBase") or die(mysql_error());
?>
<?php
$query = $_GET['query'];
// gets value sent over search form
$result_user = mysql_query("SELECT id FROM users WHERE email = '$query'") or die(mysql_error());
if (!$result_user) {
die('Could not query:' . mysql_error());
}
$user_id=mysql_result($result_user,0); // outputs first user's id
echo $user_id;
$result_accountuser = mysql_query("SELECT 'account_id' FROM accounts_users WHERE 'user_id' LIKE ('$user_id')") or die(mysql_error());
if (!$result_accountuser) {
die('Could not query:' . mysql_error());
}
$account_id=mysql_result($result_accountuser,0); // outputs first accounts_users's account_id
echo $account_id;
$result_account = mysql_query("SELECT 'account_name' FROM accounts WHERE 'id' LIKE ('$account_id')") or die(mysql_error());
if (!$result_account) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result_account,0); // outputs first accounts's account_name
?>
2.Or your query contains more than one result or more than one rows than following changes in your code will help you
<?php
//connect to database
mysql_connect("localhost", "user", "password") or die("Error connecting to database: " .mysql_error());
mysql_select_db("dataBase") or die(mysql_error());
?>
<?php
$query = $_GET['query'];
// gets value sent over search form
$result_user = mysql_query("SELECT id FROM users WHERE email = '$query'") or die(mysql_error());
while($row=mysql_fetch_array($result_user))
{
$user_id = $row['id'];
echo $user_id;
}
$result_accountuser = mysql_query("SELECT 'account_id' FROM accounts_users WHERE 'user_id' LIKE ('$user_id')") or die(mysql_error());
while($row=mysql_fetch_array($result_accountuser))
{
$account_id = $row['account_id'];
echo $account_id;
}
$result_account = mysql_query("SELECT 'account_name' FROM accounts WHERE 'id' LIKE ('$account_id')") or die(mysql_error());
while($row=mysql_fetch_array($result_account))
{
echo $row['account_name'];
}
?>
Related
Very basic but as a rookie I am struggling. The echo doesnt show any value, just the text. What am I doing wrong?
Connect.php:
<?php
$connection = mysqli_connect('test.com.mysql', 'test_com_systems', 'systems');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'swaut_com_systems');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
Get.php:
<?php
require('connect.php');
$query2 = "SELECT systemid FROM user WHERE username=test";
$result2 = mysqli_query($connection, $query2);
echo ( 'SystemID: '.$result2);
?>
Assuming you have connected to the database successfully then the query is incorrect. You must wrap all text values in quotes like this
<?php
require('connect.php');
$query2 = "SELECT systemid FROM user WHERE username='test'";
$result2 = mysqli_query($connection, $query2);
Now the mysqli_query submits the query to the database where it is run and a result set built. To see the result set you need to read the result set back from the database using one of the fetch functions for example
$row = mysqli_fetch_assoc($result2);
echo 'SystemID: ' . $row['systemid'];
If there are more than one rows in the result set you must do that in a loop like this
while ($row = mysqli_fetch_assoc($result2)){
echo 'SystemID: ' . $row['systemid'];
}
You are printing the mysqli result object. In order to printthe result you have to use:
$row = mysqli_fetch_assoc($result2);
print_r($row);
You need to collect the results of the mysqli_query using the following:
require('connect.php');
$query2 = "SELECT systemid FROM user WHERE username=test";
$result2 = mysqli_query($connection, $query2);
while ($row = mysqli_fetch_assoc($result2))
{
echo "System ID is: " . $row['systemid'];
}
I want to display the current amount of users registered in my database (it's called dalton) / the users are stored in a table in that database called simpleauth_players. It stores their name, hash, registerdate, logindate, and lastip.
I want to somehow use a PHP code that (logs me into the database) and displays the current amount of names in the database. So I can display a message like "Hey, there is currently 1,894 registered players!" inside of my HTML/PHP page. I'm kinda a novice it would be awesome if somebody could share the code and instructions.
My code:
$connection = mysql_connect('host', 'username', 'password');
mysql_select_db('database');
$query = "SELECT * FROM simpleauth_players";
$result = mysql_query($query);
$registered = "SELECT COUNT(*) FROM dalton.tables WHERE simpleauth_players = 'name' and TABLE_TYPE='BASE TABLE';
echo "$registered";
mysql_close();
This is the code I used to display the amount of registered players (AKA rows) in the simpleauth_players table.
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("dalton", $link);
if ($_GET['task'] == 'total') {
$get_db = 'simpleauth_players';
$result = mysql_query("SELECT * FROM $get_db", $link);
echo '{"task":"total","amount":"';
echo mysql_num_rows($result);
echo '"}';
}
?>
select count(*) as total_player from simpleauth_players
OR
$sql = "select * from simpleauth_players";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows();
echo "Total ".$count." Players";
Try this one assumed that your column name is language
SELECT COUNT(*) FROM simpleauth_players WHERE language = "PHP"
or if you want to get count by each language type you can use this
SELECT COUNT(DISTINCT user_id) AS Count,language FROM simpleauth_players GROUP BY language
As per your original post/question Since you have not provided us with the MySQL API you're using to connect with, here's an mysqli_ version, using MySQL's aggregate COUNT() function, which will count the number of given rows in a table:
$connection = mysqli_connect('host', 'username', 'password', 'database');
$result = mysqli_query($connection, "SELECT COUNT(*) as count
FROM simpleauth_players"
);
while ($row = mysqli_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
Edit: if using mysql_
$connection = mysql_connect('host', 'username', 'password');
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $connection);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
$result = mysql_query("SELECT COUNT(*) as count
FROM simpleauth_players", $connection);
while ($row = mysql_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
sorry to bother you all but I'm really struggling with this one:
I connect to my database fine and then I try the following mysql statements:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
However, a few lines later when I try :
echo $answer1;
I'm given only nulls :(
Can anyone give me any suggestions please?
edit:
SQL logins:
mysql_connect("correct", "username", "password");
mysql_select_db("dbname") or die(mysql_error());
everything you did is right you have just to fetch the data like this:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
while($data= mysql_fetch_array($answer1)){
echo $data['row1'];
}
And this is a complet answer, i adjust it as you need ;)
<?php
//Connect to your database
$con=mysqli_connect("db_hostname","db_user","db_password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Value of the row to select
$row2 = 'some value';
//Make select query
$result = mysqli_query($con, "SELECT row1 FROM MyTable WHERE row2='$row2'");
//Fetch datas
while($row = mysqli_fetch_array($result))
{
echo $row['row1'];
echo "<br>";
}
//Close database
mysqli_close($con);
?>
Good Luck :)
Try using MySQLi_* instead MySQL_* functions and pass the connection variable to the function calls.
If this doesn't work then you might want to try some further debugging by enabling all error reporting and dumping the global scope.
<?php
error_reporting(E_ALL); // Show all errors & warnings
$conn = mysqli_connect("server", "username", "password");
mysqli_select_db($conn, "dbname") or die(mysql_error());
$sql1 = "SELECT `row1` FROM `mydatabase` WHERE `row2` = '".$Name."';";
$query1 = mysqli_query($conn, $sql1);
$answer1 = mysqli_fetch_assoc($query1);
var_dump($GLOBALS); // Dumps all variables in the global scope
?>
add this after $answer1= mysql_query($query1);
while ($row = mysql_fetch_assoc($answer1)) {
// echo data
echo $row['row1'];
}
I am using php to get records from a mysql database using the following code:
<?php
$username="";
$password="";
$database="";
$hostname="";
$con = mysql_connect($hostname, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST['emp'])){
$emp = $_POST['emp'];
$result = mysql_query("SELECT * FROM contact_log", $con);
echo mysql_num_rows($result);
die();
while($row = mysql_fetch_array($result)){
$emp = $row['emp'];
echo $emp.'<br>';
}
die();
}
mysql_close($con);
?>
This works fine and returns the correct fields. The problem is that if I change the query to
$result = mysql_query("SELECT DISTINCT * FROM contact_log", $con);
or
$result = mysql_query("SELECT * FROM contact_log GROUP BY emp", $con);
no results are returned.
mysql_num_rows does not even return a value which indicates to me that those lines are breaking my code but I am unable to figure out how.
I doubt you want to do a distinct * on your first query. Looking at your code, you probably want:
"SELECT DISTINCT emp FROM contact_log"
And you can get more information about what is going wrong with mysql_error:
mysql_query("select * from table") or die(mysql_error())
Finally, are you sure that $_POST['emp'] is being sent? Put an echo right after that if to make sure. And just so you know, you aren't using the emp POST variable for anything other than a flag to enter that block of code. $emp = $_POST['emp']; is doing absolutely nothing.
I'm trying to call a database for the first time in PHP, and this query is causing my code to break. Note that I've tested the connection to be good. The culprit is mysql_query(). Can anybody spot what might be going wrong? The table name is "users" and the entry under the 'Name' column is 'mvalentine'. Everything matches case as far as I can tell.
dbInit.php
<?php
$connection = mysql_connect('localhost', 'root', 'password');
$db = mysql_select_db('scaleup');
if ($db) {
$user = mysql_query("SELECT ID FROM 'users' WHERE 'Name' = 'mvalentine'");
}
else {
die ('Error 01: Connection to database failed.');
}
?>
This modified code is now returning something. The value 'users' in the ajax call is now returning "false"
The value being returned should be '1'
ajax response:
<?php
include('dbInit.php');
include('objects.php'); //irrelevant, all code working properly
$layout = new Layout();
$bids = new Bids();
$out = array('layout' => $layout->_board, 'height' => $layout->_height, 'width' => $layout->_width,
'bids' => $bids->_board, 'maxBids' => $bids- >_maxBids, 'users' => $user);
$out = json_encode($out);
echo $out;
?>
It seems like you are expecting $user to contain the user ID, but it will actually contain a resource containing all of the rows returned. In order to get the user ID, you will need something like this:
$result = mysql_query("SELECT ID FROM `users` WHERE `Name` = 'mvalentine'");
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
$row = mysql_fetch_assoc($result);
$user = $row['ID'];
}
Also, take note of the other comments and answers regarding style and the preference of mysqli and PDO for this type of thing.
What is "$db" in your if statement?
To connect to your database you must use "mysql_connect" and "mysql_select_db".
For example,
<?php
$connection = mysql_connect('localhost', 'root', 'password');
$db = mysql_select_db('database_name');
if($connection)
{
if($db)
{
//query here
} else {
die("Couldn't connect to mysql database ".mysql_error());
}
} else {
die("Couldn't connect to mysql host ".mysql_error());
}
?>
Also, it is good practice to surround table and column names with the prime character like so
mysql_query("SELECT * FROM `tablename` WHERE `column_name` = 'value'");
I can't verify this right now, but I believe you may have a syntax error in your query:
mysql_query("SELECT ID FROM 'users' WHERE 'Name' = 'mvalentine'");
Column and table names, if you wish to quote them, should use the back tick:
$result = mysql_query("SELECT ID FROM `users` WHERE `Name` = 'mvalentine'");
Then change the rest of your code to actually fetch the user details:
$result = mysql_query("SELECT ID FROM `users` WHERE `Name` = 'mvalentine'") or die("Query failed");
$row = mysql_fetch_assoc($result);
$user = $row['ID'];