This question already has answers here:
How to check if a row exist in the database using PDO?
(3 answers)
Closed 5 years ago.
I'm learning PHP PDO and I need some help with codes. I have 2 Questions today.
First Question:
How can I check if row exist in table with Network_Code and Niche, if there is column with same ID to proceed, but with same ID and Niche to die message.
$network_code = $_GET[ 'ID' ];
$Niche = $_GET[ 'Niche' ];
$sql = "INSERT INTO `affiliates` (ID, Niche, Language, lockerURL, Network_Code, Google_ID) VALUES (NULL, '$Niche', '$Language', '$domain', '$network_code ', '$Google_ID')";
$query = $pdo->prepare( $sql );
$query->execute();
Second Question:
Is there any other way that I can use: $system_default[ 0 ]->column because I think that is wrong way, so I need something like this: $system_default->column
class default_system {
function __construct( $pdo ) {
$this->pdo = $pdo;
}
function getData() {
$ID = $_GET[ 'id' ];
$Niche = "clash-clans";
$query = $this->pdo->prepare( "SELECT * FROM `affiliates` WHERE `Network_Code` = '$ID' AND `Niche` = '$Niche'" );
$query->execute();
return $query->fetchAll( PDO::FETCH_OBJ ); // Return an Array of objects
}
}
$db_system = new default_system( $pdo );
$system_default = $db_system->getData();
echo $system_default[ 0 ]->lockerURL;
Below example for First Question, you can try to solve your problem certain ways below is example of it. you can read more about pdo from here
$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();
$result = $query -> fetch();
print_r($result);
For second issue
echo $system_default['lockerURL'];
and remove echo $system_default[ 0 ]->lockerURL; line
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
i'm facing this Problem when i try to select the last inserted id from Mysql table, i get the value = bool(true) instead of the values.
What i'm trying to do:
if (isset($_POST['submit'])){
if (isset($_POST['paName']) && isset($_POST['paEmail']) && isset($_POST['paTel']) && isset($_POST['aName']) && isset($_POST['Artnum'])){
if (!empty($_POST['paName']) && !empty($_POST['paEmail']) && !empty($_POST['paTel']) && !empty($_POST['aName']) && !empty($_POST['Artnum'])){
$paName = $_POST['paName'];
$paEmail = $_POST['paEmail'];
$paTel = $_POST['paTel'];
$aName = $_POST['aName'];
$Artnum = $_POST['Artnum'];
$query = "INSERT INTO crud (paName,paEmail,paTel,aName,Artnum) VALUES ('$paName','$paEmail','$paTel','$aName','$Artnum')";
if ($sql = $this->conn->exec($query)){
$id = $this->conn->lastInsertId();
$query = "SELECT * FROM crud WHERE id = '".$id."'";
$stmt=$this->conn->prepare($query);
$stmt->execute();
var_dump($stmt->execute());die();
}
but if i do the same without conditions, i get all values from the table , so that's mean my condition is wrong.
can you tell me please what i'm doing wrong ?
It seems like you are missing $this->conn->prepare() in first query. You can try this example :
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO crud (paName,paEmail,paTel,aName,Artnum)
VALUES(?,?,?,?,?);");
$sonuc = $stmt->execute([$paName,$paEmail,$paTel,$aName,$Artnum]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = "INSERT INTO crud (paName,paEmail,paTel,aName,Artnum) VALUES ('$paName','$paEmail','$paTel','$aName','$Artnum')";
$sonuc = $this->conn->execute($stmt);
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
This question already has answers here:
Insert/update helper function using PDO
(11 answers)
Closed 6 years ago.
i am upgrading one application from MySql to PDo, now the application is big so i don't want to write query every time, instead i am creating some insert, update, select etc. functions which accept dyanamic table name, with column and its value in array.
can any one sugest me how i can create this .
so far i have done is
$connection = new PDO("mysql:host=$host;dbname=$database;charset=utf8", "$user", "$password");
for select
$field = array("column1","column2");
$sql = "SELECT ".$fields." FROM ".$table." ".$whereSQL." ";
for inser
$col_val = array("column1"=>value, "column2"=>2);
$query = "insert into ".$table." (".$fields.") values (".$values.")";
$query = $connection->prepare($sql);
$query->execute();
i try to do all this but for an example in insert query i want to pass array as
$col_val = array("column1"=>value, "column2"=>2);
some code and function here which make PDO query easy and insert all column and value correctly.
i am also looking same way to perform Update query.
as you can see here tabel, column and value are totally dynamic which will be pass to function.
for this moment i am using all odd query with
$query = $connection->prepare($sql);
$query->execute();
Thank you in advance.
This is not a complete solution but that's the idea I think you could use to get closer to fix your issue.
$columns = array('column1', 'column2', 'column3')
$comma_separated = implode(",", $columns);
$columns_values = array(
'column1' => 'text1',
'column2' => 'text2',
'column3' => 'text3',
)
$values_query = "";
$index = 0
foreach ($columns as $column_name) {
if ($index == 0){
$values_query .= "'". $columns_values[$column_name]."'"
}else{
$values_query .= ", '". $columns_values[$column_name]
}
}
$query = "INSERT INTO table (". $comma_separated . ") VALUES (".$values_query.");";
Before executing the query you can use PDO to escape the string ($query) to avoid SQL injection
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been stuck on this for about 3 days now and asked multiple people about this and no one seems to have an answer to me why this is not working. I cannot figure out why they aren't binding because the bindings work on the select statement but not the update. I know for a fact that $sessCheck['userid'] and $sessCheck['hwid'] are being set because I already printed them out to check if they were null or something.
The request inbound from slim
{"userid": "1000","hwid":"TESTING"}
The function
function updateHWID(){
$request = Slim::getInstance()->request();
//$bsreq = utf8_encode();
$sessCheck = json_decode($request->getBody(), true, 9 );
$db = getConnection();
$sql = "SELECT userid,hwID FROM accounts WHERE userid = :userid";
$stuff = $db->prepare($sql);
$stuff->bindParam("userid", $sessCheck['userid']);
$stuff->execute();
$db = null;
$rows = $stuff->fetch(PDO::FETCH_ASSOC);
if ($rows['hwID'] != $sessCheck['hwid']) {
$sql2 = "UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid';";
try {
$db2 = getConnection();
$stmt = $db2->prepare($sql2);
//these two param's are not binding
$stmt->bindParam("userid", $sessCheck['userid']);
$stmt->bindParam("hwid", $sessCheck['hwid']);
$stmt->execute();
//$rt = $stmt->fetch(PDO::FETCH_ASSOC);
//$stmt->debugDumpParams();
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
This is the result incoming on the sql log
1372 Query UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid'
I've also tried this as well as using the which also didn't work
$stmt->bindParam(":userid", $sessCheck['userid']);
$stmt->bindParam(":hwid", $sessCheck['hwid']);
Then I tried this too and it didn't work
$stmt = $db2->prepare("UPDATE accounts SET hwID='?' WHERE userID = '?';");
$stmt->bindParam(1, $sessCheck['hwid'], PDO::PARAM_STR);
$stmt->bindParam(2, $sessCheck['userid'], PDO::PARAM_INT);
Take the binded parameter names out of their single quotes.
so:
$sql2 = "UPDATE accounts SET hwID=:hwid WHERE userID = :userid;";
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
I have some code that should loop through values and change entries in a table. The 5 values of the variables $change_val, $column, and $id all echo out correctly, so I assume there is something wrong with my usage of bindParam (but I am not sure what it is).
$connection = new PDO("mysql:host=localhost;dbname=logbook", $username, $password);
$perform_edit = $connection->prepare("UPDATE contacts SET :column = :value WHERE name_id = :name_id");
[Definition of Arrays]
for ($i = 1; $i <= 5; $i++) {
if (!empty($_POST[ $change_array[$i]])) {
$change_val = $_POST[$change_array[$i]];
$column = $column_array[$i];
$id = $_POST["name_id_ref"];
$perform_edit->bindParam(":column", $column, PDO::PARAM_STR);
$perform_edit->bindParam(":value", $_POST[$change_array[$i]], PDO::PARAM_STR);
$perform_edit->bindParam(":name_id", $_POST["name_id_ref"], PDO::PARAM_INT);
$perform_edit->execute();
}
}
The $_POST statement is there because the value I want is actually passed from another file. When I place appropriate echo statements within the loop, though, they all print out their correct value.
I've also tried bindValue, but that did not work either. I see no errors and things at least compile smoothly—just not as they should. Nothing in the table is changed.
What's wrong here?
You cannot use place holders for table or column names it would defeat the purpose of preparing a statement ahead of time if the structure of that statement changed.
You would need to pre-build your prepare statement with the correct column names, whether you name them by hand, string replacement, or implode a list of column names.
I don't have an environment to test on right now but something like:
//Some random values and DB column names
$arrLocation = array ('Victoria','Washington','Toronto','Halifax','Vancouver');
$arrName = array ('Sue', 'Bob', 'Marley', 'Tim', 'Fae');
$arrColumn = array (1 => 'name', 2 => 'age', 3 => 'location');
/* Build column & named placeholders
* $strSet = '`name` = :name, `age` = :age, `location` = :location';
*/
$strSet = '';
foreach ($arrColumn as $column) {
$strSet .= "`$column` = :$column, ";
}
$strSet = rtrim($strSet, ', ');
$connection = new PDO($dsn, $user, $pass);
/*
* Prepared statement then evaluates to:
* UPDATE `table` SET `name` = :name, `age` = :age, `location` = :location
* WHERE `id` = :id;
*/
$stmt = $connection->prepare("UPDATE `table` SET $strSet WHERE `id` = :id;");
$arrChange = array (
1 => $arrName[(rand(0, count($arrName)-1))],
2 => rand(0, 30),
3 => $arrLocation[(rand(0, count($arrLocation)-1))]
);
$idToUpdate = 1;
$stmt->bindParam(':id', $idToUpdate, PDO::PARAM_INT);
foreach($arrChange as $key=>$value) {
$stmt->bindValue(":$arrColumn[$key]", $value);
}
$stmt->execute();
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 9 years ago.
I want to get all the list of registered players from an array
here is my function
function UpdateContact()
{
try {
$conn = $this->GetDBConnection();
$linkedInId = trim($_REQUEST['linkedInId']);
$statement = $conn->prepare('UPDATE users SET linkedInId = :linkedInId WHERE linkedInId = :linkedInId');
$statement->bindParam(':linkedInId', $linkedInId, PDO::PARAM_STR);
$statement->execute();
//$updatedTime = time() - 120;
$ids = implode(",",$_POST['ids']);
// $ids = (abc,def,geh,ijk,lac);
$statement = $conn->prepare('SELECT * FROM users WHERE linkedInId IN (:ids)');
$statement->execute($ids);
$conn = null;
if (!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
return false;
else
return $row;
} catch(PDOException $e) {
throw $e;
}
}
Just return false
Maybe because i am not able to bind the array with PDO Statement?
How can I fix this solution, i might want to add more binding parameters too later on, so i don't want to do execute($ids) either.
I have tried bindParam(':ids',$ids) too but of no avail
$items = array();
//$statement->bindParam(':updatedTime', $updatedTime, PDO::PARAM_STR);
foreach ($id as $ids)
{
$statement = $conn->prepare('SELECT * FROM users WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
if(($row = $statement->fetch(PDO::FETCH_OBJ)))
$items[] = $id;
}
I think it would make more sense to parse the array/list and perform the select for each id in the array/list.
Pseudo code:
init resultArray;
For x in List
select * from database where ids =: x
if result
add result to resultArray
return resultArray
But that's just the basic way of doing it, I'm not sure if you can do it more advanced.