Get a value from database using PDO php - php

I read few topics about my issue here and it didnt solve anything..
I don't understand where I am wrong in my code..
So I need to get the name from a database when my vt_id equal a number..
function recup_nom_visite($VT_ID){
$pdo = PDO2::getInstance();
$requete = $pdo->query("SELECT VT_NOM FROM CRF_VISITE WHERE VT_ID = :vt_id ");
$requete->bindValue(':vt_id' , $VT_ID);
$requete->execute();
if($result = $requete->fetch(PDO::FETCH_ASSOC)){
$requete->closeCursor();
return $result['NOM_VISITE'];
}
return false;
}
I tried this too :
function recup_nom_visite($VT_ID){
$pdo = PDO2::getInstance();
$requete = $pdo->query("SELECT VT_NOM FROM CRF_VISITE WHERE VT_ID ='".$VT_ID."' ");
$req = $requete->fetch();
$result = $req;
return $result;
}
but all result it returns is "array" or nothing..
Do I miss something ?
Thank you for help

function recup_nom_visite($VT_ID){
$sql = "SELECT VT_NOM FROM CRF_VISITE WHERE VT_ID = ?";
$stmt = PDO2::getInstance()->prepare($sql);
$stmt->execute(array($VT_ID));
return $stmt->fetchColumn();
}
This is how PDO intended to work.
PS. Do not delete your questions. Deleted question cannot be answered, you know.

Related

How to count your user userID to count/select a row in a table?

I'm making a function that i have to check if a userid is in this table already: if not he has to get into another page yet. But for some reason I get "NULL" back instead of the number of the userID.
my class:
public function countHobbies($userID){
try{
$conn = Db::getConnection();
$statement = $conn->prepare("select * from hobby where userID = '".$userID."'");
$userID = $this->getUserID();
$statement->execute();
$aantal = $statement->fetchAll(PDO::FETCH_ASSOC); //
$aantal->execute();
}
catch(throwable $e){
$error = "Something went wrong";
}
}
and this is on my html page:
$userArray = $_SESSION['user_id'];
$userID = implode(" ", $userArray);
$hobby = new Hobby();
$count = $hobby->countHobbies($userID);
if($count == false){
echo "no";
//header('Location: hobby.php');
}
else{
echo "yes";
}
There are at least two things you need to fix:
Always use parameter binding on the SQL statement. It may not be a security problem in this particular instance, but do get into the habit of using prepared statements. Because otherwise you'll find yourself in situations where you should've but didn't. https://www.php.net/manual/en/security.database.sql-injection.php
The $userID variable must be assigned before it is used.
In the end, it could look like this:
$userID = $this->getUserID();
$statement = $conn->prepare("select * from hobby where userID = ?");
$statement->bind_param("s", $userID);

Php use of bindParam in SQLite

When I try to add something to the sqlite databse the result is always false. Where is the error? I don't get an exception so I think the code is correct by syntax. Please help me
public function add(ChatMessage $chatMessage){
$stmt = $this->db->prepare('INSERT INTO chatmessage(id,authorName,message) VALUES(:id,:authorName,:message)');
$stmt->bindParam(':id',$id);
$stmt->bindParam(':authorName',$authorName);
$stmt->bindParam(':message',$message);
$id = $chatMessage->getID();
$authorName = $chatMessage->getAuthorName();
$message = $chatMessage->getMessage();
$result = $stmt->execute();
if($result == false) return false;
$chatMessage->setID($this->db->lastInsertId());
$chatMessage->setAuthorName($this->db->lastInsertId());
$chatMessage->setMessage($this->db->lastInsertId());
$this->chatMessages[]=$chatMessage;
}

Button to update MySQL column not working

I want to update my database with an SQL statement once someone clicks a button on the website. I've tried something, no success. Can you guys help me ? Here's the code:
http://pastebin.com/D0S83Jgh
Don't know if I made this question correctly, I'm new here.
Your prepared statement is wrong.
The code I use with pdo to do a query is this:
$sqlUpd = $upd->prepare("UPDATE league_signups SET approved='1' WHERE id = :id");
$q->bindParam(':id', $id, PDO::PARAM_STR);
$q->execute();
Should work like a charm.
Get this code out of the main loop: while($row = $q->fetch(PDO::FETCH_ASSOC)) {}
<?php
include('pdoconnect.php');
$id = isset($row['id'];
if(isset($_REQUEST['approve']))
{
$sqlUpd = "UPDATE league_signups SET approved='1' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
if(isset($_REQUEST['unapprove']))
{
$sqlUpd = "UPDATE league_signups SET approved='0' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
?>
Put this code after the loop ending or the beginning of your code...
The data you want to update comes from the checkbox am I right? then you may want to make a loop to update all the values selected with checkbox to the corresponding action 'approve' or 'unapproved'
remove include('pdoconnect.php'); its utterly unnecessary if you are including this file from the beginning already
<?php
// checkbox[] it's an array...
$UpdateIDs = (isset($_REQUEST['checkbox'])) ? $_REQUEST['checkbox'] : [];
// check if $_REQUEST['approve'] is set else check if $_REQUEST['unapprove'] is set else set $approve to null;
$approved = (isset($_REQUEST['approve']) ?
$_REQUEST['approve'] :
(isset($_REQUEST['unapprove'])) ? $_REQUEST['unapprove'] : null;
if(!is_null($approved))
{
try {
foreach($UpdateIDs as $ID)
{
$stmt = $upd->prepare("UPDATE league_signups SET approved=:approved WHERE id=:id");
$stmt->execute([
':approved' => $approved,
':id' => $ID
]);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}

user_exists function using mysqli

I';m working on changing my code from using MySQL to MySQLi, and its all seemed to be going fine, but I hit a bit of a wall, I'm currently stuck on changing over my function user_exists and I have tried looking into different reason why and what's going wrong but it seems to be the query, i did var_dump($result) and got the response NULL and was told that its down to my query then, so i tried an sql search on phpmyadmin and got a result so im thinking its down to me binding $username to the ? as the errors i get is of that it cannot find the username im trying to log in with.
function user_exists($username) {
$db = $GLOBALS['db'];
$username = trim($username);
//sql
$sql = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ?";
//Prepare
$result = $db->prepare($sql);
//Bind
$result->bind_param('s', $username);
//execute
$result->execute();
//Bind-Results - the 2 codes below are noted out cause im not sure they are needed but have tried with and without them
//$result->bind_result($user_id);
//$result->fetch();
if (false === $result) {
return false;
}
return ($result->num_rows === 1);
}
i can provide the code to my signin.php but im not sure it would be useful as it all worked before i started changing the function.
if someone could point out what, where and why its not working, can you please explain so i can understand so Im good for the future and maybe able to help others out.
You need to call $result->store_result() before checking the number of rows. mysqli_stmt::store_result() will load the result set from the prepared statement so you can access results and properties.
EDIT: This is sort of how I would do it though (untested):
function user_exists($username) {
global $db;
//sql
$sql = "SELECT `user_id` FROM `users` WHERE `username` = ?";
//Prepare
if (!($result = $db->prepare($sql)) return false;
//Bind
if (!$result->bind_param('s', trim($username))) return false;
//execute
if (!$result->execute()) return false;
//Bind-Results
$result->bind_result($user_id);
$result->fetch();
$result->close();
return $user_id ?: false;
}
Here is how my user_exist() function ended up
function user_exists($username) {
$db = $GLOBALS['db'];
//sql
$sql = "SELECT user_id FROM `users` WHERE `username` = ?";
//Prepare
$result = $db->prepare($sql);
//Bind
$result->bind_param('s', $username);
//execute
$result->execute();
//store result
$result->store_result();
if (false === $result) {
return false;
}
return ($result->num_rows === 1);
}
I hope this will help someone. But if any of the code shouldn't be there, i apologise in advance, the code was there for a reason at one point but as im learning all this still, no one advised me that it shouldnt be there.. hope it helps

Return mysqli query result as an array in PHP

I've been searching the internet for a while now, but since I'm new to MySQLi, I cannot solve this problem myself. This is my code so far. I want to return the result as an array.
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo)) {
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error.' in query: '.$userinfo;
} else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$var] = &$$var;
}
return $parameters;
}
$stmt->close();
}}
Hopefully someone can help me get this code working, or help me find an alternative.
Have you looked at using fetch_array
http://php.net/manual/en/mysqli-result.fetch-array.php
Working from your code
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo))
{
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute())
{
echo $stmt->error.' in query: '.$userinfo;
}
else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$parameters = array();
while ($row = $stmt->fetch_assoc()) {
$parameters[] = $row;
}
$stmt->close();
return $parameters;
}
$stmt->close();
}
}

Categories