I'm trying to include variables in my MYSQL SELECT WHERE query.
I want to be able to use variables, as well as the false symbol "!="
For example:
select * from XXX
where id != '$id'
Why is this not working, and how can I make this work?
It's better you use mysqli prepared statement or PDO since mysql_* functions are deprecated in recent PHP versions. Check how your query looks with mysqli prepared statement.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("SELECT * XXX WHERE id != ?");
$stmt->bind_param( "d", $value);
// 'd' is a format integer, for string use 's'
$stmt->execute();
$stmt->bind_result($col1);
// then fetch and close the statement
As you are asking how can pass variable id in mysql query so check below, other wise so many guys have answered you for php etc.
set #id=4;
select * from XXX
where id != #id;
If you are using this code in php, you can use this
$query = "select * from XXX where id != {$id}";
OR
$query = "select * from XXX where id != '".$id."'";
If you are trying to use these variables in phpmyadmin, I think that is not possible.
Related
I want to use a function after WHERE
like this it works
$sql = "SELECT * FROM Prodotti WHERE Id=10";
what if i want the id to be in the URL link?
the link example is this: https://www.try.org/product.php?signup=98
this way it's not working
$sql = "SELECT * FROM Prodotti WHERE strpos($fullUrl, signup=Id)";
You can get the id by using the $_GET superglobal:
$id = (int) $_GET['signup']; // (int) makes sure it is an integer and no string
Now in order to make it work within your query you first need to make the input secure.
You can make an input secure by using mysqli_real_escape_string but since you need an integer and not a string it is better to use a prepared statement.
In your query you can than do
$sql = "SELECT * FROM `Prodotti` WHERE `Id` = $id";
Use backticks around table and column names to prevent mysql reserved word error.
Example of prepared statement:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$id = (int) $_GET['signup'];
if ($stmt = $mysqli->prepare("SELECT * FROM `Prodotti` WHERE `Id` = ?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $id);// i for integer s for string
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
// Do something with the fetched data
/* close statement */
$stmt->close();
}
You can get the signup parameter from the url like this:
$signup = $_GET['signup'];
and then use it in your query:
$sql = "SELECT * FROM Prodotti WHERE Id = '$signup'";
but this is not secure, i suggest you also google for "php mysql prepared statements"
I have a table structure like this:
sender| receiver| message|date|time
----------------------------------
How do I select all the messages written on the same date, with them appearing at the top, just like Facebook Chat?
I've tried something like this:
<?php
$con=mysql_connect("localhost","root","");
$db=mysql_select_db ("chat",$con);
$query=" select * from chat where sender='$send'
and receiver='$rec' order by date";
$result=mysql_query($query);
while($r2=mysql_fetch_array($result))
echo "<div>{$r2['date']}</div>";
{
echo"<div>{$r2['message']}</div>";
}
?>
You're trying to run an SQL query directly from PHP, which you can't do - you'll need to connect to your database first. Then you need to pass the $send and $rec variables to your database, preferably through prepared statements to prevent SQL injection.
It depends on whether you're using MySQLi or PDO as to exactly how you should do that, but I'll assume you're not using the mysql_ constructor, as that was deprecated as of PHP 5.5, and is removed in PHP 7.
As such, here's an example of how to do this through MySQLi with prepared statements:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$stmt = $mysqli->prepare(
"SELECT * FROM tablename WHERE sender = ? && receiver = ?");
$stmt->bind_param("ss", $send, $rec);
// "ss' is a format string, each "s" means string
// Each variable gets passed to the question marks, in order
$stmt->execute();
$stmt->bind_result($result);
You then have the results stored in $result, and are free to manipulate from there.
Hope this helps! :)
I have a problem with mysql_query
I tried to find members who are online, there is a field "Online" in the members table are always updated with the time server. This is the query.
$ now = time ();
$ olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$ now')> 10"));
in phpmyadmin there are 7 members in accordance with the above query. tp I get a value of 0. what is wrong with my code. tq for the answer and sorry for bad english
You should try and always use Mysqli these days as before long Mysql will be gone completely. Mysqli example of your code:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$now = time(); // The time now for query calc
$gender = "Man"; // Gender for query
$stmt = $mysqli->stmt_init(); //Initialise statement
$stmt->prepare("SELECT * FROM members WHERE gender = ? AND (online - ?)> 10"); //Prepare the query
$stmt->bind_param('ss', $gender, $now); //Assign the query parameters
$stmt->execute(); // Execute the query
$stmt->store_result(); // store result of prepared statement
echo $stmt->num_rows;
$stmt->free_result(); //free up the $stmt var
Variable names cannot contain spaces, so your variable names are invalid. It should be $now or $_now and NOT $ now. See Language variable basics for more information:
Correct code :
$now = time ();
$olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$now')> 10"));
Also , avoid using mysql_ functions cause they are deprecated. Use mysqli_ or PDO.
I am not sure, I have clearly understood your question.
If I have understood correctly, you want to display the online available members.
Do you have any flag for checking if the member online or not? If there is a flag then use that flag and filter by online status. This how we have to do for chat operations.
I am not sure, why you going with subtraction.
$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query('UPDATE table SET field = field + ($userlogin)');
Is this the right way of getting userlogin from the post request and then inserting it to my SQL query?
Stop using outdated functions and use PDO instead.
$stmt = PDO::prepare('UPDATE table SET field = field + :field');
$stmt->execute(array('field' => $_POST["userlogin"]));
Read some information about PDO.
In short: it escapes your data for you, is quite consistent across databases and generally just easier.
you should use mysql_real_scape_string() just after connecting to database ...
so change your code to this :
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
$userlogin = mysql_real_escape_string($_POST["userlogin"]);
mysql_query("UPDATE table SET field = '$userlogin'");
Try like this.
$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query("UPDATE table SET field = value where user='$user'");
Try this
mysql_query("UPDATE table SET field = field + ('$user')");
However,
You might be updating all the fields in your table because you have no where in your UPDATE clause
Shouldn't it rather be
mysql_query("UPDATE table SET field = field WHERE user= '$user'");
I think you want to INSERT instead of using Update. Why field = field + ($userlogin)? This will concatenate the values. And one more thing please use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("INSERT INTO tanlename (field) VALUES (?)");
$stmt->bindParam(1, $user);
$stmt->execute();
?>
Use mysql_real_escape_string() after mysql connection and
Use double quotes
mysql_query("UPDATE table SET field = field + ({$userlogin})");
Use mysqli_query for you queries(notice the i) and use prepared statements. Using prepared statements is more secure than using straight queries and including the variable in the query string. Moreover, mysql will be deprecated soon. Example :
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
In my website users can submit posts and delete their posts.
To delete a post, they follow the link /posts.php?deletid=X where X is the id of the post in database (for example: 1).
When clicked, it will run the following:
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".mysql_real_escape_string($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}
The problem is that it's vulnerable to the 1=1 SQL injection. If they type into the address bar /posts.php?deletid=1 OR 1=1;
it will delete all posts on database.
In this question: How can I prevent SQL injection in PHP?, I realized I need to use mysqli statements, and I tried to make it work but with no success..
Can someone please tell me exactly how I can prevent this with mysqli?
You need to have the value in quotes for mysql_real_escape_string to have any useful effect.
$sql = "DELETE from `posts` WHERE `id`='".mysql_real_escape_string($deleteid)."'";
Alternatively, instead of mysql_real_escape_string, which is intended for strings, try intval.
With MySQLi and prepared statements you do not need to worry about this, as a parameter cannot be replaced by 1 OR 1=1 (or if it is provided as the parameter value, then it’s interpreted as a string).
By using prepared statements, the mysql_* functions are on there way out and soon tobe deprecated, one should not be writing new code with these functions, refactor your code.
PDO
<?php
$db = new PDO("mysql:host=localhost;dbname=yourDB", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** prepare the SQL statement ***/
$query = $db->prepare("DELETE from `posts` WHERE `id`=:id;");
/*** bind the paramaters ***/
$query->bindParam(':id', $deleteid, PDO::PARAM_INT);
/*** execute ***/
$query->execute();
header('Location: posts.php');
exit();
?>
mysqli
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("DELETE from `posts` WHERE `id`=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $deleteid);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
header('Location: posts.php');
exit();
?>
One thing first: if you can, it would be wise not to use mysql_* but e.g. mysqli_* functions or PDO, since the first are outdated. There you can use placeholders (?) instead of string concats. You don't have to care for quoting yourself there.
The easiest option in your example code would be to run all numbers through integer parsing (use intval).
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".intval($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}