<!-- QUERY -->
$insertstatement = 'SELECT count(*) co FROM `tbl_user` WHERE username="'.$username.'" AND password="'.$password.'"';
$query123 = mysql_query($insertstatement) or trigger_error(mysql_error()." ".$insertstatement);
while($r = mysql_fetch_array($query123)){
extract($r);
}
<!--GET-->
$co = (int)$co;
$name = $r['name'];
if($co == 1){
$result = array();
$result[] = array("name" => $name,"status" => 1);
}
header('Content-type: application/json');
echo json_encode($result);
if username available / user registered .. the result name is empty.
name :
status : 1
You write the query to get the count of the table having the uername and password given. Then how can you get the name using that query? Please study the things that you did before posting in the forums
1) Your not selecting name column . your only counting the row using count(*)
2) Mysql_* is derprecated try to use mysqli_* or PDO
3) Use prepared statement oR pdo when you dealing with user entered data to avoid sql injection
query :
SELECT count(*) as co, name FROM `tbl_user` WHERE username='username' AND password='password'
Update 1:
You already used extract to change it to variable . so directly access like this $co = (int)$co;
// $name = $r['name']; //no need this line
if($co == 1){
$result = array();
$result[] = array("name" => $name,"status" => 1);
}
Related
I have a website that manages points of interest, using PHP and MySQL. I decided to look at MySQL's Spatial Data features instead of saving the coordinates in two separate fields.
I managed to get the inserting of data into the database using the following:
// Update new records
$query = "UPDATE users SET users_address = :uaddress, users_placeid = :uplace, users_coords = POINTFROMTEXT(:location) ";
$query .= "WHERE users_id = :uid ";
// echo "Query: $query <br>";
$stmt = $conn->prepare($query);
$stmt->execute(array(':uaddress' => $users_address,
':uplace' => $users_placeid,
':location' => $location,
':uid' => $users_id));
$result = $stmt;
Now I want to read the data and get the coordinates out, using PHP and PDO. There does not seem to be any examples on the Internet for using PDO, PHP and MySQL for spatial data.
My normal SELECT code is:
$stmt = $conn->prepare("SELECT * FROM users WHERE users_id = :uid ");
$stmt->execute(array(':uid' => $users_id));
$result = $stmt;
if ($result->rowCount() > 0) {
foreach($result as $row) {
$users_address = $row['users_address'];
$users_placeid = $row['users_placeid'];
$users_lat = $row['x.users_coords'];
echo "Lat: $users_lat <br>";
}
}
I've tried various options and each one gives an error. The code above returns:
Notice: Undefined index: x.users_coords
I want to stick to using SELECT * instead of SELECT users_address, etc. if possible.
The other option is to just return to using two fields for the coordinates, but that makes it more difficult to do distance measurements etc later.
Any idea how to extract Latitude and Longitudes?
After much frustration I managed to solve the problem. You have to specify the spatial data in the SELECT string and then it is easy to read the data. Here is full code to read the data:
$stmt = $conn->prepare("SELECT *, X(users_coords) AS users_lat, Y(users_coords) AS users_long FROM users WHERE users_id = :uid ");
$stmt->execute(array(':uid' => $users_id));
$result = $stmt;
if ($result->rowCount() > 0) {
foreach($result as $row) {
$users_address = $row['users_address'];
$users_placeid = $row['users_placeid'];
$users_lat = $row['users_lat'];
// echo "Lat: $users_lat <br>";
$users_long = $row['users_long'];
// echo "Long: $users_long <br>";
}
}
?>
I have switched over to the mysqli_ extension for PHP, and I have ran into a bit of an issue.
I have 2 databases. 1 database I am only allowed read privileges, the other I have all privileges. My end goal is to read what I need from database 1, and put it in a table in database 2.
I use a join on database 1 to get all the information I need. I then loop through the results with a while loop. I have a unique id (domainid) in both databases. Where I am encountering the issue is inside the while loop once I have the domainid from the read-only database, I need to check if it exists inside my all-privileges database. I am just unsure of how to accomplish this?
Here is the code:
require 'db/connect.php';
require 'db/connect2.php';
if($result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
")){
if ($count = $result->num_rows) {
while($row = $result->fetch_object()){
$domainid = $row->domainid;
$domain = $row->domain;
$email = $row->email;
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $row->domainid);
$result2->execute();
$result2->bind_result($domainid2);
//$result2->fetch();
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($domainid == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}
}
}
This is what I have tried, but was unsuccessful.
EDIT
Second attempt putting the results into an array then looping through them. The array is correct when I print them out. The issue is with the 2nd execute(); command.
$result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
");
$domainid_arr = array();
while($row = $result->fetch_object()){
$domainid_arr[] = array(
'domainid' => $row->domainid,
'domain' => $row->domain
);
}
foreach ($domainid_arr as $d) {
echo $d['domainid'], $d['domain'], '<br>';
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $d['domainid']);
$result2->execute();
$result2->bind_result($domainid2);
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($d['domainid'] == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}
I will pass the query into this function query("SELECT * FROM table_name");
And the function is
public function query($sql) {
$resource = mysql_query($sql, $this->link_web);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $i;
unset($data);
return $query;
} else {
return true;
}
} else {
trigger_error('Error: ' . mysql_error($this->link_web) . '<br />Error No: ' . mysql_errno($this->link_web) . '<br />' . $sql);
exit();
}
}
I want to add tenent_id = '1' in SELECT query also for INSERT query. Likewise I need to do it for UPDATE.
I want to bring the query like this
SELECT * FROM table_name WHERE tenent_id = 1 and user_id = 1
INSERT INTO table_name('tenant_id, user_id') VALUE('1','1')
UPDATE table_name SET user_id = 1 WHERE tenant_id = '1'
Can anyone give me the idea about how to insert tenant_id in select, insert and update
Thanks in advance
It's better practice to use the correct mysql functions rather than just a query function.
For example, if you want to cycle through many items in a database, you can use a while loop:
$query = mysql_query("SELECT * FROM table WHERE type='2'");
while($row = mysql_fetch_array($query)){
echo $line['id'];
}
This would echo all the IDs in the database that have the type 2.
The same principle is when you have an object, using mysql functions, you can specify how you want the data to return. Above I returned it in an array. Here I am going to return a single row as an object:
$query = mysql_query("SELECT * FROM table WHERE id='1'");
$object = mysql_fetch_object($query);
echo $object->id;
echo $object->type;
echo $object->*ANY COLUMN*;
This would return as:
1.
2.
Whatever the value for that column is.
To insert your data, you don't need to do "query()". You can simple use mysql_query($sql).
It will make life much easier further down the road.
Also, its best to run one query in a function, that way you can handle the data properly.
mysql_query("INSERT...");
mysql_query("UPDATE...");
mysql_query("SELECT...");
Hope this helps.
The simple answer is: just add the condition to your query. Call query("SELECT * FROM table_name WHERE tenant_id = 1 and user_id = 1").
If you're concerned about escaping the parameters you pass to the SQL query (which you should be!), you can either do it yourself manually, e.g.
$query = sprintf("SELECT * FROM table_name WHERE tenant_id = %d", intval($tenant_id));
query($query);
Or better use prepared statement offered by mysqli extension (mysql_query is deprecated anyway):
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE tenant_id = ?");
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// ...
}
If I still haven't answered your question, you can use a library to handle your queries, such as dibi:
$result = dibi::query('SELECT * FROM [table_name] WHERE [tenant_id] = %i', $id);
$rows = $result->fetchAll(); // all rows
The last option is what I would use, you don't need to write your own query-handling functions and get query parameter binding for free. In your case, you may utilize building the query gradually, so that the WHERE condition is not part of your basic query:
$query[] = 'SELECT * FROM table_name';
if ($tenant_id){
array_push($query, 'WHERE tenant_id=%d', $tenant_id);
}
$result = dibi::query($query);
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();
Is there any way to store mysql result in php variable? thanks
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
then I want to print selected userid from query.
Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
There are a couple of mysql functions you need to look into.
mysql_query("query string here") : returns a resource
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.
Links:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-fetch-array.php
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
$query="SELECT * FROM contacts";
$result=mysql_query($query);
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
http://php.net/manual/en/pdo.prepared-statements.php PDO
$query = "SELECT username, userid FROM user WHERE username = 'admin' ";
$result = $conn->query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$arrayResult = mysql_fetch_array($result);
//Now you can access $arrayResult like this
$arrayResult['userid']; // output will be userid which will be in database
$arrayResult['username']; // output will be admin
//Note- userid and username will be column name of user table.