I have, for example, this URL with spesific paramater in the end:
http://example.com/index.php?id_user=84759832475
The value [id_user=**84759832475**] is created by myself and I have declared it inside my script.
$txtemail = strip_tags(isset($_POST['txtemail'])) ? strip_tags($_POST['txtemail']) : '';
$txtemail=strip_tags($txtemail);
$txtname = strip_tags(isset($_POST['txtname'])) ? strip_tags($_POST['txtname']) : '';
$txtname =strip_tags($txtname);
$id_user="84759832475";
$stmt="SELECT * FROM table_name WHERE emailz=:txtemail AND namez=:txtnamez";
$pgdata = $myDb->prepare ($stmt);
//bind semua variabel login dalam parameter
$pgdata->bindParam(':txtname', $txtname, PDO::PARAM_STR,31);
$pgdata->bindParam(':txtemail', $txtemail, PDO::PARAM_STR,31);
//eksekusi statemen prepare tadi
$pgdata->execute();
//cek & lihat hasil
//$cekdata = $pgdata->fetchColumn();
if(!$pgdata->rowCount()> 0){
$pgdata = $myDb->prepare('INSERT INTO table_name (namez,emailz,userid) VALUES (:txtname,:txtemail,?????)');
$pgdata->execute(array(':namez'=>$txtname, ':emailz'=>$txtemail, ':userid'=>$id_user));
In this case, the question mark ?????? makes me confused of what to write.
I'm sorry if my English is too bad to explain this question.
Just add another named placeholder inside that other prepared statement, just like the others:
$txtemail = isset($_POST['txtemail']) ? strip_tags($_POST['txtemail']) : '';
$txtname = isset($_POST['txtname']) ? strip_tags($_POST['txtname']) : '';
$id_user = "84759832475";
$stmt = 'SELECT COUNT(id) AS total FROM table_name WHERE emailz = :txtemail AND namez = :txtnamez';
$pgdata = $myDb->prepare($stmt);
$pgdata->bindParam(':txtnamez', $txtname, PDO::PARAM_STR);
$pgdata->bindParam(':txtemail', $txtemail, PDO::PARAM_STR);
$pgdata->execute();
$result = $pgdata->fetch(PDO::FETCH_ASSOC);
if($result['total'] > 0){
$pgdata = $myDb->prepare('
INSERT INTO table_name (namez,emailz,userid)
VALUES (:txtname, :txtemail, :userid)
');
// just add another named placeholer :userid
$pgdata->execute(array(':txtname'=> $txtname, ':txtemail'=> $txtemail, ':userid' => $id_user));
}
Related
This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 1 year ago.
I am trying to sum a colomn based on the IDs selected from a table that i put in a array. For some reasom only the first ID is used in the Where clausule. When I echo the variable all the ids are there. What am i doing wrong?
$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT
id
FROM account
WHERE level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
$stmt3->bind_param("ss",$usernamesession,$groupname);
$stmt3->execute();
$result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
$countid = implode(',', $counttheid); // contains all the ids !!
}
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i",$countid);
$stmt->execute();
$stmt->bind_result($row['totalcash']);
while($stmt->fetch()) $sumcash = $row['totalcash'];
echo $sumcash; // Somhow only the sum of the first ID of the array !!
echo $countid;// all the ids from the array !!
Not only for the in, but the number of bind parameters will need to match as well.
Try with this example for the code from the while to the execute:
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
// $countid = implode(',', $counttheid); // contains all the ids !!
}
$in = str_repeat('?,', count($counttheid) - 1) . '?';
$types = str_repeat('i', count($counttheid));
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN ($in)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$counttheid);
$stmt->execute();
At the bind_param, the part with ...$counttheid, the ... portion is the argument unpacking operator.
Is there a way to choose row name in mysql table from a variable in Php code? For example, instead of SELECT email, I want SELECT email_2 based on my if statement like this:
$value == "";
if(true){
$value = email
SELECT $value from....
else{
$value = email_2
SELECT $value from....
}
This is my php code:
$stmt = $conn->prepare("SELECT email from account_data_base WHERE test = ?");
$stmt->bind_param("s", $test);
You could use a variable to select the column you want. You cannot use the statement on column names.
$test = 'your_value';
$column = 'email'; // column by default
if ($your_condition_is_true) {
$column = 'email_2';
}
$stmt = $conn->prepare("SELECT $column FROM account_data_base WHERE test = ?");
$stmt->bind_param("s", $test);
i need some help , i have simple code like count rows in php, i use PDO ,
so i check if rowCount > 0 i do job if no other job but i have it in foreach function, in first step i get true result but in other i get invalid
so i think it is function like a closeCursor() in PDO but i try and no matter . maybe i do it wrong ?
it is part of my code
public function saveClinicCalendar($post){
$daysItm = '';
$Uid = $post['Uid'];
$ClinicId = $post['ClinicId'];
$type = $post['type'];
$resChck = '';
foreach($post['objArray'] as $arr){
foreach($arr['days'] as $days){
$daysItm = $days.",".$daysItm;
}
$daysItm = substr($daysItm, 0, -1);
$dateTime = $arr['dateTime'];
$sqlChck = 'SELECT * FROM clinic_weeks WHERE dates = :dates AND Uid = :Uid AND category = :category AND Cid = :Cid AND type = :type';
$resChck = $this->db->prepare($sqlChck);
$resChck->bindValue(":dates",$dateTime);
$resChck->bindValue(":Cid",$ClinicId);
$resChck->bindValue(":type",$type);
$resChck->bindValue(":Uid",$Uid);
$resChck->bindValue(":category",$Uid);
$resChck->execute();
$co = $resChck->rowCount();
if($co > 0){
/*UPDATE*/
$sql = 'UPDATE clinic_weeks SET dates = :dates ,time = :time, Cid = :Cid, type = :type, Uid = :Uid, category = :category ';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}else{
/*INSERT*/
$sql = 'INSERT INTO clinic_weeks (dates,time, Cid,type,Uid,category) VALUES (:dates,:time, :Cid,:type,:Uid,:category)';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}
$res->execute();
$resChck->closeCursor();
$resChck = null;
$daysItm = '';
}
}
what i am doing wrong?
many thanks to Barmar, he suggest me a true answer.
here is a code
$sql = "INSERT INTO clinic_weeks
(`timestam`,`time`,dates,Cid,type,Uid,category)
VALUES
('$timestamp','$daysItm','$dateTime','$ClinicId','$type','$Uid','$Uid')
ON DUPLICATE KEY UPDATE `time` = '$daysItm' ";
I use there "ON DUPLICATE KEY UPDATE" and it`s work perfectly!
instead a big code top of page i make a two line of code.
I want to pull a list of data from a table based on the requests by a user.
1. $query = "SELECT * FROM users LIMIT 10";
2. $query = "SELECT * FROM users WHERE fname = ? LIMIT 10";
3. $query = "SELECT * FROM users WHERE fname = ? AND mname = ? LIMIT 10";
4. $query = "SELECT * FROM users WHERE fname = ? AND mname = ? AND lname = ? LIMIT 10";
If no parameter is provided, query (1)
If first name provided, query (2)
If first and middle name provided, query (3)
If all are provided, query (4)
It's hard for me to know which one the user will request.
How do I prepare, bind, execute, and fetch data of the chosen one from above?
UPDATE: more details.
<?php
$db = new mysqli("It's all OK");
$query = "SELECT * FROM users LIMIT 10";
$fname = (isset($_POST['fname']) AND !empty($_POST['fname'])) ? trim($_POST['fname']) : "";
$mname = (isset($_POST['mname']) AND !empty($_POST['mname'])) ? trim($_POST['mname']) : "";
$lname = (isset($_POST['lname']) AND !empty($_POST['lname'])) ? trim($_POST['lname']) : "";
if(!empty($fname) AND empty($mname) AND empty($lname)){
$query .= " WHERE fname = ? LIMIT 10";
}elseif(!empty($fname) AND !empty($mname) AND empty($lname)){
$query .= " WHERE fname = ? AND mname = ? LIMIT 10";
}elseif(!empty($fname) AND !empty($mname) AND !empty($lname)){
$query .= " WHERE fname = ? AND mname = ? AND lname = ? LIMIT 10";
}
?>
Given all the details, query is built but it's hard to predict what the user will request.
I have done:
$stmt = $db->prepare($query);
Now I have a problem binding the unpredictable parameters.
Please help.
I guess you have variables somewhere like fname, mname, and lname. Put them in an array like
$options = ['fname' => $fname, 'mname' => $mname, 'lname'=> $lname];
$defaults = ['fname' => '', 'mname' => '', 'lname'=> ''];
$options = array_merge($defaults, $options);
$options = array_diff($options, []);
$query = "SELECT * FROM users";
foreach ($options as $key => $value){
$query .= " AND $key = ?"
}
$query .= ' LIMIT 10';
There is a brilliant solution
$fname = (!empty($_POST['fname'])) ? trim($_POST['fname']) : NULL;
$mname = (!empty($_POST['mname'])) ? trim($_POST['mname']) : NULL;
$query = "SELECT * FROM users WHERE
(? is null OR fname = ?)
AND (? is null OR mname = ?)
AND so on
LIMIT 10";
A variable will be used in the query only if its value is not null.
this way you will need only one query and one set of parameters for any number of parameter combinations.
$stmt = $db->prepare($query);
$stmt->bind_param('ss', $fname, $fname, $mname, $mname);
$stmt->execute();
(You need to bind every variable twice though).
But this approach will leave you with only one query and with straight call to bind_param() with constant number of variables.
But if you still want to bind unknown number of variables, here is the solution.
Your own solution won't work if only lname provided or fname and lname but no mname.
Sometimes I think that sharing knowledge on SO is a biggest waste of time.
Thanks all for your effort to answer. I really appreciated it.
After several attempts, I manage it to work.
$stmt->prepare($query);
if(!empty($fname) AND empty($mname) AND empty($lname)){
$stmt->bind_param("s", $fname);
}elseif(!empty($fname) AND !empty($mname) AND empty($lname)){
$stmt->bind_param("ss", $fname, $mname);
}elseif(!empty($fname) AND !empty($mname) AND !empty($lname)){
$stmt->bind_param("sss",$fname,$mname,$lname);
}
$stmt->execute()
and bind result, fetch it that's all.
It might not be the best answer, but it does work.
Again, thanks all.
I'm trying to edit data(stored in DB). This is display.php. First it displays data from DB (if no data then blank fields). Then edit button to edit DB.
<html>
<body>
<?php
if(!isset($_POST['edit_pro']))
{
?>
//get data from DB and display in table.
<form>
<input type="submit" name= "edit" value="edit">
</form>
<?php
}
else
{
?>
<form name="edit_DB" action="edit.php">
//edit ...2 <select> fields and 1 text field.
//submit button
</form>
<?php
}
?>
And in edit.php
i simply update the DB. But what if i want to change only 1 field.(problem is all fields gets updated).Here's edit.php
<?php
include_once 'db_connect.php';
$db_con = dbConnect("dbname");
$uid = $_SESSION['uid'];
if(isset($_POST['edit']))
{
$c = $_POST['c'];
$s = $_POST['list'];
$t = $_POST['nm'];
$a = $_POST['a'];
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c,$s,$t,$uid));
header("Location:display.php");
}
?>
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
this query means:
update table user
for each row in this table where u_id = [some value]
set fields C and S and T to some other distinct values
so, your query updates 3 fields at one time, and it is ok, as it what it should do
if you want to change this logic, to update only some fields you need to change query and arguments, for example if you want to change only c use:
$sql = "UPDATE `user` SET `c` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c, $uid)); // this array binds values to question marks, so count should be the same, we have 2 ? - we must use 2 variables
for c AND t:
$sql = "UPDATE `user` SET `c` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute();
if you don't know exactly how many arguments will be, you need dynamic query building, like:
$arr = array();
$sqlA = array();
if (isset($_POST['c']) && $_POST['c']) {
$arr[] = $_POST['c'];
$sqlA[] = '`c`=?';
}
if (isset($_POST['s']) && $_POST['s']) {
$arr[] = $_POST['s'];
$sqlA[] = '`s`=?';
}
if (isset($_POST['t']) && $_POST['t']) {
$arr[] = $_POST['t'];
$sqlA[] = '`t`=?';
}
if (count($arr)) {
$sql = 'UPDATE `user` SET '.implode($sqlA, ',').' where u_id = ?';
$arr[] = $uid;
$q = $db_con->prepare($sql);
$q->execute($arr);
}
That means that WHERE clause of the request doesn't work. Check if you passing a quotation marks " in you variable $t so you close $sql before WHERE clause