I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);
Related
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
So I have the below code that I'm trying to run partly as a login script, and partly to gather some information for another program. I don't get any errors with the script, I just don't get any information from the second and third mysql_fetch_array which I read is a common problem but that should only apply to the same table. Even so, I followed the recommended advice and used mysql_data_seek to reset the $result. I've also tried using different $result and $row variables but I still don't get any data back from those queries. Any thoughts on how I can do this?
$result = mysql_query("SELECT * FROM user WHERE username = '$username'");
$row = mysql_fetch_array($result);
$salt = $row['salt'];
$id = $row['id'];
$usergroup = $row['usergroupid'];
$mysql_pass = $row['password'];
$md5_pass = md5($password.$salt);
mysql_data_seek ($result, 0);
if($mysql_pass == $md5_pass)
{
$result = mysql_query("SELECT teamid FROM tmnt_members WHERE teamid = '$id'");
$row = mysql_fetch_array($result);
$team = $row['teamid'];
$captain = $row['leader'];
$cocaptain = $row['coleader'];
mysql_data_seek ($result, 0);
$result = mysql_query("SELECT * FROM tmnt_teams WHERE teamid = '$team'");
$row = mysql_fetch_array($result);
$teamname = $row['teamname'];
}
You're missing your coleader and leader fields in your second query. Your three queries can be written as one quite simply.
SELECT *
FROM user u, tmnt_members m, tmnt_teams t
WHERE u.username = '$username'
AND m.teamid = u.id
AND t.teamid = m.teamid
Or if you would like to keep the authentication a separate query, you could do SELECT * FROM user WHERE username = '$username' followed by:
SELECT *
FROM tmnt_members m, tmnt_teams t
WHERE m.teamid = '$id'
AND t.teamid = m.teamid
While writing this, I noticed there probably is an error in your second query. The condition teamid = '$id' seems pretty strange. Currently, you're fetching the team which has an ID that is the one of the user. That can't be correct, or if it is, your database structure is very, very strange. I guess it should be something like memberid = '$id'.
Also notice that without the corrections suggested in my first paragraph, this query is asking the database to fetch the ID of a team which has the ID $id. In other words, you could've just used $id directly if that query was correct.
Moreover, doing a SELECT * isn't the best practice; it's better to enumerate all the fields you want explicitly. If you change your column names or do some other modifications to your database, your query may still work, but may not do what you expect it to do.
I've converted your code to MySQLi at least. I have quoted my comments inside. And did try to clean your code. Try this:
<?php
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA INSIDE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$username=mysqli_real_escape_string($con,$_POST['username']); /* ASSUMING $username COMES FROM A POST DATA. JUST REPLACE IF NECESSARY */
$result = mysqli_query($con,"SELECT * FROM user WHERE username = '$username'");
while($row = mysqli_fetch_array($result)){
$salt = mysqli_real_escape_string($con,$row['salt']);
$id = mysqli_real_escape_string($con,$row['id']);
$usergroup = mysqli_real_escape_string($con,$row['usergroupid']);
$mysql_pass=mysqli_real_escape_string($con,$row['password']);
$md5_pass = md5($password.$salt); /* MAKE SURE YOU HAVE $password AND $salt VARIABLES DECLARED ABOVE */
if($mysql_pass == $md5_pass)
{
$result2 = mysqli_query($con,"SELECT teamid, leader, coleader FROM tmnt_members WHERE teamid = '$id'"); /* ADDED leader AND coleader */
while($row2 = mysqli_fetch_array($result2)){
$team = mysqli_real_escape_string($con,$row2['teamid']);
$captain = mysqli_real_escape_string($con,$row2['leader']);
$cocaptain = mysqli_real_escape_string($con,$row2['coleader']);
$result3 = mysqli_query($con,"SELECT * FROM tmnt_teams WHERE teamid = '$team'");
while($row3 = mysqli_fetch_array($result3)){
$teamname = mysqli_real_escape_string($con,$row3['teamname']);
} /* END OF THIRD LOOP */
} /* END OF SECOND WHILE LOOP */
} /* END OF IF MYSQL_PASS IS EQUALS TO MD5_PASS */
/* IS THIS WHERE YOU WANT TO PRINT YOUR RESULTS? */
echo $id." ".$usergroup." ".$team." ".$captain." ".$cocaptain. " ".$teamname;
} /* END OF WHILE LOOP */
?>
I apologize for not knowing how else to do this. I went to add to my other question, and I could not figure out how to append this to it.
I am trying to apply your answer to the previous question in another place.
In this instance I have a bit more going on but thought I could do the same thing as above -with the adjustment of changing id for user_name, since the ids would not match table to table, but the user_name does. I know I am biting off a lot for my first project but I really like this coding stuff. Hope I am not pulling on too many shirt tails. Thanks for your help.
Heres the code. Its placing the same user_name in every row(like the previous question was)
<?php
$Var1 =$_POST['Var1'];
require("connection.php");
mysql_query("UPDATE table1 SET actor = '$Var1'");
$result = mysql_query("SELECT * FROM table2 WHERE subject ='$Var1'");
while($row = mysql_fetch_array($result))
{ $un = $row['user_name'];
$a =$row['subject'];
$a_val = $row['subject_val'];
$sql=mysql_query("UPDATE table3 SET user_name='$un', subject='$', subject_val= $a_val WHERE user_name=".$row['user_name']);
}
mysql_close($connection);
?>
This is the last time I answer this kind of question. I'm also adding some optimization.
<?php
var expires = (isset($_POST['var1']) ? $_POST['var1'] : die("no VAR");
require_once("connection.php");
mysql_query("UPDATE table1 SET actor = '$var1'") or die("I cannot run , reason : ".mysql_error());
$result = mysql_query("SELECT * FROM table2 WHERE subject ='$var1'") or die("I cannot run , reason : ".mysql_error());
while($row = mysql_fetch_array($result)) {
extract($row); // field name as variable , content as value , so be sure that the fields have the right name
/*
$user_name = $row['user_name'];
$subject =$row['subject'];
$subject_val = $row['subject_val'];
*/
$sql="UPDATE table3 SET user_name='".$user_name."', subject='".$subject."', subject_val= ".$subject_val." WHERE user_name='".$user_name."'";
mysql_query($sql) or die("I cannot run , reason : ".mysql_error());
}
mysql_close();
?>
Changed the key of third table to user_name - then
$sql="UPDATE table3 SET user_name='".$user_name."', subject='".$subject."', subject_val= ".$subject_val." WHERE user_name='".$un."'";
worked!!
thanks for the help!!
I have the following code and it should return just one value (id) from mysql table. The following code doesnt work. How can I output it without creating arrays and all this stuff, just a simple output of one value.
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = map_query($query);
echo $result;
I do something like this:
<?php
$data = mysql_fetch_object($result);
echo $data->foo();
?>
You have to do some form of object creation. There's no real way around that.
You can try:
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
//$result = map_query($query);
//echo $result;
$result = mysql_query($query); // run the query and get the result object.
if (!$result) { // check for errors.
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result); // get the single row.
echo $row['id']; // display the value.
all you have is a resource, you would still have to make it construct a result array if you want the output.
Check out ADO if you want to write less.
Not sure I exactly understood, what you want, but you could just do
$result = mysql_query('SELECT id FROM table WHERE area = "foo" LIMIT 1');
list($data) = mysql_fetch_assoc($result);
if you wish to execute only one row you can do like this.
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo $row[0];
there have been many ways as answered above and this is just my simple example. it will echo the first row that have been executed, you can also use another option like limit clause to do the same result as answered by others above.
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)