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

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';

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();

Compare values from two different tables, if equal then display [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 6 years ago.
Improve this question
I have a variable called $row['mykey'] that was genterated from a query on table one, I have echoed
it to my page and it does display the value I'm looking for. Now I need to use this varible to set my new query
on table two, to only display results if it matches contractor_lock from table two. $stmt1 one works fine to display the entire table, but I want to use $stmt2 but get no data results. Thanks for any help!
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt1 = $conn->prepare("SELECT client_id, companyname, contact, contractor_lock FROM table_two");
$stmt2 = $conn->prepare("SELECT client_id, companyname, contact, contractor_lock FROM table two WHERE contractor_lock = $row['mykey']");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
}
You have to concatenate $row['mykey'] to stmt2 instead of including it directly because it might be interpreted as a string.
It should be like this
$stmt2 = $conn->prepare("SELECT client_id, companyname, contact, contractor_lock FROM table two WHERE contractor_lock = ?");
$stmt2->execute($row['mykey']);

Bind array into select query [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 try to bind an array of values in this case $ownco in another select query but it wont work. How can I realize it, that all values becomes checked/passed in the second query?
<?php
$hostname = 'localhost';
$user = 'root';
$password = '';
$username = $_COOKIE['username'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=searchfood", $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id_post
FROM comments
WHERE username = $username
ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$ownco = $res->fetchAll();
}
} catch (PDOException $e) {
echo $e->getMessage();
}
$userid = $_COOKIE['userid'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=searchfood", $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id, autorid, autor, date, longitude, latitude, title, text, town, time
FROM posts
WHERE id = $ownco
ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$resultcom = $res->fetchAll();
}
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
There are several problems with your question.
First of all, you accepted the the answer that doesn't answer it. Cheating on the rules?
Second, your first query will never work, due to wrong SQL syntax AND lack of prepared statements.
Third, $ownco doesn't contain the data structure you expect.
Fourth, to bind an array with PDO is quite simple question, explained in many answers already and even in PDO tag wiki.
Fifth, you don't need the second query at all. Instead you have to use JOIN in the first query.
Change your second query as below
$sql = "SELECT id, autorid, autor, date, longitude, latitude, title, text, town, time
FROM posts
WHERE id in (" . implode(",",$ownco) . ")
ORDER BY id DESC";

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.

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

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 />
}
}

Categories