how can i put a php variable into mysql command [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
$id1 = $_POST['number']; //here i am getting a php variable called number
$result = mysqli_query($con, "SELECT id,main FROM first WHERE ?how can i put that number right here?");
I am getting a variable from another page using ajax and i should put it into mysql command.How can i do that?

Here's an example of using prepared statements:
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysql('localhost', 'username', 'password', 'db');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $user, $pass);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $user . "'s level of priviledges is " . $result;
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
Source
I strongly suggest researching prepared statements early on.

option 1.Good to go for Prepared statements
option 2."SELECT id,main FROM first WHERE id=$id"
When a string is specified in double quotes, variables are parsed within it.

$result = mysqli_query($con, "SELECT id,main FROM first WHERE your_db_field = $id1");
OR
$result = mysqli_query($con, "SELECT id,main FROM first WHERE your_db_field = " . $id1 . ");
Should work just fine.
However you should consider using Stored Procedures to avoid any security vulnerabilities...

//Get ur name from Post Request
$number=$_POST['number'];
$query="SLEECT * FROM TABLE_NAME WHERE colunm_name='$number"; (or)
$query="SLEECT * FROM TABLE_NAME WHERE colunm_name='".$number."'";
$result=mysql_query($con,$query)
//Using Prepared Statement
$stmt = $dbh->prepare("SELECT * FROM TABLE_NAME where COLUMN_NAME= ?");
if ($stmt->execute(array($_GET['number']))) {
while ($row = $stmt->fetch()) {<br />
print_r($row);<br />
}
}

Related

Why doesn't my variable work in my SELECT statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
session_start();
$username = $_SESSION['username'];
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME,
DBUSER, DBPASS);
function keygrabber($username) { //You need to pass a variable into this
function
global $db; //Gain access to the $db variable, which is out of scope due to
being inside of a function
$stmt = $db->prepare("SELECT * FROM keys WHERE username='$username'");
//Prepare the query
$stmt->execute(); //Execute the query
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch the query results
var_dump($results); //Dump the results
}
keygrabber($username);
So If I change username='$username'; to username='myactualusername';, it works, i.e. it shows no errors or anything.
I'm basically trying to get all data out of keys that matches the user's username. I'll change this to userID In the future but now variables are not working so I am unable to progress.
Thanks for the help
try like this
$stmt = $db->prepare("SELECT * FROM keys WHERE username='$username'");
Hope it will make sense..
You should not use php var in SQL (you are at risk for sqlinjection) you should use prepared statementes and param binding
be sure that your $username contain a valid value firts and then
$stmt = $db->prepare("SELECT * FROM keys WHERE username=:username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
try this
prepare("SELECT * FROM keys WHERE username=?");
$stmt->execute([$username]);
$rows = $stmt->fetchAll();

Turning a HTML form input into an PDO variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want the user to specifiy a number, this number will be used in my SQL statement when connecting to the database. If the user inputs five I want the five first rows in the table to be displayed.
If i write "SELECT * FROM TABLE WHERE ID <= 5" it works, but my variable is being fetched from a form. When I use $variable = $_POST['variable'] and print it out using "SELECT * FROM TABLE WHERE ID <= $variable" no results are being returned. Why is that?
you need to bind that variable if you use PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT * FROM TABLE WHERE ID <= :id");
// bind params
$stmt->bindParam(":id", $_POST['variable']);
$stmt->execute();
// fetch with
// $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "OK";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
According to http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Looked through the code once again, just a simple typo:
Works with:
$sql = 'SELECT * FROM sql WHERE id <= ' . $items;
Before this I had
$sql = 'SELECT * FROM sql WHERE id <= $items';

Prepared Statement not working- Blank page

I have this code
$con = new mysqli('####', '####', '####', '####');
if(mysqli_connect_errno()){
echo 'Connection Failed:' . mysqli_connect_errno();
exit();
}
//Variables
$user = $_POST['username'];
$zone = $_POST['password'];
$pass = strtoupper(hash("whirlpool", $zone));
//Prepare
if($stmt = $con -> prepare("SELECT * FROM `accounts` WHERE Username=? AND Key=?")){
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();
$stmt -> bind_results($result);
$stmt -> fetch();
if($result) {
$_SESSION['username'] = $user;
$url = 'home.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';
} else {
echo 'Login Failed';
}
}
?>
I am new to Prepared statements and I cannot get it to work.
Upon trying to log in I just get a blank white page with no error. I know I am connected to the db because if I remove the prepared statement and do it the unsecured way everything logs in just fine.
Please note. I have just been looking up tutorials on prepared statements so I can learn to code more securely. I am in no way a pro with this. Any tips would be greatly appreciated.
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in
C:\xampp\htdocs\newsystem\loginadd.php
That's because you select * (all fields). You should be more specific about the fields you want to get (for example SELECT id FROM ...).
Have a look at examples on PHP doc: 2 fields are selected, 2 parameters for bind_result().
According to #AbrikChakraborty comment you just need add backticks to your field name:
if($stmt = $con -> prepare("SELECT * FROM `accounts` WHERE Username=? AND `Key`=?")){
and according to #caCtus comment:
$stmt -> bind_result($result);
and if you really want to bind unknown number of fields returned you can check this answer or just use PDO.
Verify the actual query, if it fetches the result. I doubt the query itself returns empty result.
"SELECT * FROM `accounts` WHERE Username=$user AND Key=$pass"

how to make mysqli prepared statement and fetch result? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I can't understand how to create a prepared statement, and all tutorials I have seen was fetching only column.
My normal sql query
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM files WHERE id=$id ") or die(mysql_error());
$row = mysql_fetch_array($result);
$name = $row['name'];
$date = $row['date'];
Please show me how to create a prepared statement and how to fetch more than one column and insert the date into variables.
First of all it's not a good idea to use SELECT * in production. Instead specify needed columns explicitly. Take a look at https://stackoverflow.com/a/65532/1920232.
Now your code might look like
$id = $_GET['id'];
$db = new mysqli('localhost', 'user', 'password', 'dbname');
$sql = 'SELECT name, date FROM files WHERE id = ?'; //specify columns explicitly
if ($stmt = $db->prepare($sql)) { //create a prepared statement
$stmt->bind_param('i', $id); //bind parameters
$stmt->execute(); //execute query
$stmt->bind_result($name, $date); //bind result variables
$stmt->fetch(); //fetch values
}
$db->close();
echo $id, ' ', $name, ' ', $date;
Note: All error handling intentionally skipped for brevity.

Echo Mysqli query with POST variable?

want i want is to query my db with post variable in the query. It's not really working for me, does anyone know how to do it properly?
Here is what i have so far.
$query = "SELECT column FROM `table` WHERE 'name' = '$_POST[checkname]'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
Any help is appreciated. Thanks guys.
Mysqli supports prepared statements, which protect against sql injection attacks. It would look like this:
/* Create a prepared statement */
$stmt = $mysqli -> prepare("SELECT column FROM table WHERE name=?");
/* Bind parameters */
$stmt -> bind_param("s", $_POST['checkname']);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $result;
Check the manual for more info.
A quick rundown, in response to the comment:
In $stmt->prepare("..."), you're forming your query, and you hold the place of any variables you intend to use with a "?"
In $stmt -> bind_param(...), you're binding the variables to their corresponding question mark. The first argument is the type, the following arguments are the variables. If you were using a string and an integer, inside the parenthesis it would look like "si", $stringVar, $intVar
In $stmt -> bind_result(...) you are stating what you are binding the results to. If the query was for a name and age, inside the parethesis would look like $name, age
In $stmt->fetch(), you're fetching the result. If it was multiple rows returned, you would do something like:
while($stmt->fetch()) {
//code here
}
Alternatively, you could use PDO. It would look something like this:
/* Create a prepared statement */
$stmt = $pdo->prepare("SELECT column FROM table WHERE name=:checkname");
/* Bind parameters */
$stmt->bindParam(':checkname', $_POST['checkname']);
/* Execute it */
$stmt->execute();
/* Fetch results */
$obj = $stmt->fetchObject();
echo $obj->column;
Check the manual for more info.
//it is apsulutly
// work
if(isset($_POST['checkname']))
{
$post = mysql_real_escape_string(trim($_POST[' checkname ']));
$query = "SELECT column FROM `table` WHERE name = '$post'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch_all($result);
echo implode($cod[0]);
echo implode($cod[1]);//For particular cell
}
it works, just try it out like this
following your code...
if(isset($_POST['checkname']))
{
//to avoid SQL injections
$post = mysql_real_escape_string(trim($_POST['checkname']));
$query = "SELECT column FROM `table` WHERE name = '$post'";``
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
}

Categories