Mysql query variable syntax - php

I am trying to pass a variable to a very basic mysql query. but php doesnt return a true value. nothing.
i have checked everything
the problem is here.
the syntax of $a varible typing into mysql query
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id='$a' LIMIT 1");
when i change $a to 22 it returns a value otherwise nothing.
exact query is here...
$a=$this->post_id;
$result = mysql_query('SELECT floatingnumber FROM posts WHERE id="'.$a.'" LIMIT 1')or die(mysql_error());
$row = mysql_fetch_row($result);
$sdfa=$a.'-'.$row[0];
$sdfa returns "86 - " without quotes 86 - space
so the problem is on the mysql fetch row please help

Have you tried echoing the query to see what the real value of $a is?
echo "SELECT id,floatingnumber FROM posts WHERE id='$a' LIMIT 1";
Have you tried checking for errors?
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id='$a' LIMIT 1") or die(mysql_error());
Also, you shouldn't even be using mysql_* as it's deprecated.
This is how you'd do it in PDO:
$stmnt = $db->prepare("SELECT id,floatingnumber FROM posts WHERE id=:id LIMIT 1");
$stmnt->bindValue( ':id' , $a , PDO::PARAM_INT );
$stmnt->execute();
$result = $stmnt->fetchAll(PDO::FETCH_ASSOC);

typically when I'm writing in double quotes, simply putting in the variable works:
"... $1 ..."
but also, I originally learned it with brackets
"... {$1} ..."
you can try that. also, a handy way to write queries is store the query string in its own variable so you can easily print out the query and see what you wrote before submitting.
$query = "SELECT id,floatingnumber FROM posts WHERE id=$a LIMIT 1";
$result = mysql_query( $query );
This helps identify things like this.

try this
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id='".$a."' LIMIT 1");
if your $a is a number then do like that
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id= $a LIMIT 1");
EDIT :
your code is right
$row = mysql_fetch_row($result);
$sdfa=$a.'-'.$row[0];
the problem is in your sql or table because there is no floatingnumber where id is 86 .

Related

Select id and matching username order?

How do you know if $id1 matches the row of $user1 or $user2? Is this the correct way to do this query?
$sql = "SELECT id FROM users WHERE username='$user1',username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$id1 = $row[0];
$id2 = $row[1];
can I use ORDER BY username='$user1' ?
As I stated in comments, your syntax is invalid. A WHERE clause uses AND or OR as separators, not commas.
So what you need to do here, is adjust your query and compare them thereafter:
Sidenote: You may need to add extra columns to the SELECT as that may throw you an undefined offset notice. Also make sure that if you have more than 2 rows, your LIMIT of 2 may fail on you.
$sql = "SELECT id FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$id1 = $row[0];
$id2 = $row[1];
if($user1 == $id1) {
echo "User 1 is the same ";
}
if($user2 == $id2) {
echo "User 2 is the same";
}
References:
http://dev.mysql.com/doc/refman/5.7/en/select.html
http://dev.mysql.com/doc/refman/5.7/en/where-optimizations.html
As per your edit:
can I use ORDER BY username='$user1'
No, you need to use ORDER by column_name, and not an "equal to" and a variable.
If your column name is the same as the variable, then that is possible but I won't know that for sure until your db schema / contents are known.
The syntax is:
ORDER BY column accepts ASC or DESC depending on the order you want.
Reference:
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
If your query has any user intervention/input, you will need to use a prepared statement, since that would leave you open to an SQL injection.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement

Last ID not showing

I am trying to grab the largest ID number from the database. The output should be 15 but it shows 1. My PHP script:
$sql = "SELECT MAX(id) AS id FROM employees";
$sql = $db->prepare($sql);
$lid = $sql->execute();
I am outputting it here:
<input type="number" name="id" value="<?php echo $lid; ?>" disabled>
I have also tried:
$sql = "SELECT id FROM employees ORDER BY id DESC LIMIT 1";
I tried the command on phpMyAdmin. It worked fine. The output was 15. So, I suspect that there are no problems in the query.
What is the problem, then?
You should FETCH i.e., $sql->fetch(PDO::FETCH_ASSOC);
So, You shall have something like
$sql = "SELECT MAX(id) FROM employees";
$sql = $db->prepare($sql);
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
Note : Simply $lid = $sql->execute(); means it will assign whether the query is executing or not.
As your query is executing it is returning true which is 1
Update : If you are not binding any values you don't even need to prepare, you shall fetch it directly like Adelphia said
$sql = $db->query("SELECT MAX(id) FROM employees");
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
No need for prepared statements since it's a static query.

mysql query fails if name has more then 1 words

I began to create a website for my small real estate business.
I played a bit with functions http://www.php.net mysql and I managed to make a page accessed via AJAX and returning html content for the search engine.
I have a database already populated with apartments and houses
The problem is that if the apartment name is "apartment" I return html content if "apartment with 3 rooms" it no longer write anything.
I do not understand where I was wrong:
<?php
$search = $_GET['selected'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('houses', $link);
function searchHouse($search, $link){
$query = "select * from houses where name=$search limit 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query2 = "select * from houses_info where house_id=$row[id]";
$result2 = mysql_query($query2);
$row = mysql_fetch_assoc($result2);
return $row;
}
$result = searchHouse($search, $link);
echo $result['house_sq'];
echo "<br>";
echo $result['house_rooms'];
echo "<br>";
echo $result['house_bathrooms'];
echo "<br>";
echo $result['house_address'];
?>
you should know if you "played" with php.net that mysql_* functions are deprecated and are no longer maintained. It's a red box on top of the page informing you that.
you have a big MySQL injection hole there, you are not escaping $string at all
your problem is that you are not adding quotes to $string like: '$string'
you should stat using PDO to get rid of the bad code and SQL Injections holes.
you can wrap those 2 selects into a single select:
<?php
function searchHouse($search, $link){
$search = mysql_real_escape_string($search);
$query = "select * from houses_info where house_id IN (select * from houses where name='".$search."' limit 1)";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
?>
since you are already building that website you can start moving to PDO, read this tutorial, your code will be more like this:
<?php
$db = new PDO('mysql:host=localhost;dbname=houses;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$search = $_GET['selected'];
function searchHouse($search){
global $db;
$query = $db->prepare("select * from houses_info where house_id IN (select * from houses where name=:search limit 1)");
$query->execute(array(':search' => $search));
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
$result = searchHouse($search);
?>
try:
$query = "select * from houses where name='".mysql_real_escape_string($search)."' limit 1";
and remember to always sanitize user input before passing it to sql to avoid sql injections.
Your first query should be:
$query = "select * from houses where name like $search% limit 1";
Strings need to be quoted in queries. Also, this is vulnerable to MySQL injection, make sure to escape $search with mysql_real_escape_string. Or even better yet use MySQLi or PDO instead of the old mysql_ functions.
$query = "select * from houses where name=$search limit 1";
Should be:
$query = "select * from houses where name='$search' limit 1";
Although you REALLY need to escape $search because it came from a user, even if they aren't malicious, any search queries with a single quote in it will break;
$search = $_GET['selected'];
Should be:
$search = mysql_real_escape_string($_GET['selected']);
(Anybody have the copy paste handy with the links to tutorials for MySQLi/PDO and such?)

I am having problem in "fetching" only one entry from mysql

I want only one single data from that DB but I am not able to "take it out of" $res.
$sql = "SELECT * FROM `study_stuffs_extra`.`tid` ORDER BY `id` DESC LIMIT 1 ";
$res = query($sql);
$tid = $res['tid'];
I have also tried a while loop to do so, but "couldn't do it". Is there any other method to "do it"?
try
$sql = "SELECT * FROM `study_stuffs_extra`.`tid` ORDER BY `id` DESC LIMIT 1 ";
$res = mysql_query($sql);
$res=mysql_fetch_array($res);
$tid = $res['tid'];
SELECT tid FROM study_stuffs_extra ORDER BY `id` DESC LIMIT 1
Also, check what query returns. Is that a mysql result? the whole result set? a row? Do some print_r to see what you get. Check for db errors after executing queries.
You may need to subscript the first member of $res, assuming it is an array.
$firstRow = $res[0];

While returning no results

I've got the following query in an existing script - but it's not always returning a value even though it should based off what's in the database. There are plenty of things in the database it SHOULD be grabbing - they are there.
Don't see anything wrong with it - but I barely do this anymore :) See anything?
$query = "SELECT id FROM xtags WHERE tag_id = '$tagid' ORDER BY RAND() Limit 2";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$query = "SELECT * FROM xtable WHERE id = '$row[id]'";
$result = mysql_query($query) or die(mysql_error());
$row2 = mysql_fetch_assoc($result);
echo $row2[title];
}
$result is being used inside the loop and outside, try making a new variable inside and not reusing the outside one.
You're reusing the $result variable inside the loop which overwrites the value for use in the while condition. Use a different name for $query and $result inside the loop.
I don't know if is ok, but you are using $result twice, one before the "while" and another inside the "while".
I would personally split the string and the variable $row.
Why not use var_dump() to see $row and the other variables ???
I don't understand what you are trying to do actually, but try this:
$query = "SELECT id FROM xtags WHERE tag_id = '".$tagid."' ORDER BY RAND() Limit 2";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$query2 = "SELECT * FROM xtable WHERE id = '".intval($row[id])."'";
$result2 = mysql_query($query2) or die(mysql_error());
$row2 = mysql_fetch_assoc($result2);
echo $row2[title];
}
Problem solved - did a join statement.

Categories