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']);
Related
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();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am building a website and I want to display user reviews in a Bootstrap carousel. I want to display only the latest 3 feedbacks. The latest review has to have a class "active". In order to do that, I need the last id not just after inserting into the table, but throughout the whole website. I have tried this so far:
$sql = "SELECT MAX(id) FROM comments";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$last_id = $row["id"];
}
I know there's a way to get the last_id after inserting a new row, but I will always need the last variable. Can anyone help me with this?
SELECT id FROM `comments` order by id desc limit 1
when you use SELECT MAX(id) FROM comments field name in result will be MAX(id) and $row["id"]; will not work
if you want to use MAX use it something like this SELECT MAX(id) as id FROM comments
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
//I guess this is the line you're lookin for
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
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';
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";
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.