I am having issue trying to figure out how to add another column to my where clause not sure how to do it. I need it to have FIRSTNAME and LASTNAME since the existing database has two columns.
<?php
header('Content-Type: application/json');
try {
$dbName = "C:\\inetpub\\wwwroot\\fpdb\\staffing.mdb";
$db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)};charset=UTF-8; DBQ=$dbName; Uid=; Pwd=;");
}
catch (PDOException $e) {
echo $e->getMessage();
}
$Employee_Name= trim($_POST["Employee_Name"]);
$params = array( ':FIRSTNAME' => $Employee_Name);
$query = $db->prepare("
SELECT * FROM tbl_USERS
WHERE FIRSTNAME=:FIRSTNAME");
$query->execute($params);
$result = $query->fetch(PDO::FETCH_ASSOC);
$EMPLOYEE_NUMBER=trim('EMPLOYEE_NUMBER');
$rc= $result[$EMPLOYEE_NUMBER];
echo json_encode ($rc);
?>
$Employee_Name= trim($_POST["Employee_Name"]);
$params = array( ':FIRSTNAME' => $Employee_Name, ':LASTNAME'=>$Employee_Lastname );
$query = $db->prepare("
SELECT * FROM tbl_USERS
WHERE FIRSTNAME=:FIRSTNAME and LASTNAME=:LASTNAME");
I'm guessing the column names above but generally the right idea
Related
I am trying to create an http_build_query array but it is inserting some diferent characters, this is my Code:
function Conectar(){
try{
$opcoes = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
$con = new PDO("mysql:host=localhost; dbname=*****;", "*****", "*****", $opcoes);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $con;
} catch (Exception $e){
echo 'Erro: '.$e->getMessage();
return null;
}
}
$pdo = Conectar();
$sql = "
SELECT dominio
FROM dominios_extraidos
WHERE verificado='0' LIMIT 3
";
$stm = $pdo->prepare($sql);
$stm->execute();
while ($rows = $stm->fetch()) {
$query = http_build_query(array(
'domains' => array(
''.$rows['dominio'].'',
)
));
print_r($query);
}
Creating this output:
domains%5B0%5D=0002021web.com.br%0Adomains%5B0%5D=007import.com.br%0Adomains%5B0%5D=00pet.com.br%0A
But this is my desire output:
domains%5B0%5D=0002021web.com.br&domains%5B1%5D=007import.com.br&domains%5B2%5D=00pet.com.br
My desire output could be generated manually using this code:
$query = http_build_query(array(
'domains' => array(
'0002021web.com.br',
'007import.com.br',
'00pet.com.br',
)
));
print_r($query);
Thank you for your time :)
You want to build up your array properly first, so that it looks like your manual array, then use http_build_query:
$domains = ['domains' => []];
while ($rows = $stm->fetch()) {
$domains['domains'][] = trim($rows['dominio']);
}
$query = http_build_query($domains);
print_r($query);
Create an array of domains in the loop and then after the loop is complete pass it as a param to the http_build_query().
while ($rows = $stm->fetch()) {
$doms[] = trim($rows['dominio']);
}
$query = http_build_query( ['domains' => $doms] );
print_r($query);
This will produce
domains%5B0%5D=0002021web.com.br%0A&domains%5B1%5D=007import.com.br%0A&domains%5B2%5D=00pet.com.br%0A
which equates to
domains[0]=0002021web.com.br
&domains[1]=007import.com.br
&domains[2]=00pet.com.br
0A decoded is \n or Line Feed;
perhaps try sanitizing first with
$query= trim($query, "\x00..\x20\x7F");
this code remove ASCII character from 00 to 20 hex and 7f hex
Function getUsers_Test() can retrieve data with the limit of 10 rows only while my getUsers_Orig() cannot retrieve any records **my record in the database is almost 50 rows*. No error, no warning. (PHP version 5.5.12)
function getUsers_Test(){
$sql = "SELECT TOP 10 a.user_name, a.user_level, a.user_status, b.* FROM user_access a, user_details b WHERE a.emp_code = b.emp_code ORDER BY a.id DESC";
try{
$data = array();
$db = null;
$db = connectDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
}catch(PDOException $e){
$data['message'] = "Error: " . $e;
}
echo json_encode($data);
}
function getUsers_Orig(){
$sql = "SELECT a.user_name, a.user_level, a.user_status, b.* FROM user_access a, user_details b WHERE a.emp_code = b.emp_code ORDER BY a.id DESC";
try{
$data = array();
$db = null;
$db = connectDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
}catch(PDOException $e){
$data['message'] = "Error: " . $e;
}
echo json_encode($data);
}
function connectDB() {
$dbuser = "myusername";
$dbpass = "mypassword";
$dbh = new PDO('odbc:databaseName', $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
You could try catching a general exception instead of the PDOException
try
{
// ...
} catch (\Exception $e) {
// ...
}
The size of data is not a problem here, the data I was fetching has a special character (A‘ for Ñ). I use to add charset UTF-8 in my connection but still, I wasn't able to fetch it.
This problem occurs when I perform Generate Script and extract data from MSSQL instead of Backup and Restore. So when I execute the script from the Generate Script feature of MSSQL, the character changed and I didn't notice it.
Thank you for being here!
i want to be able to select acc_id from account_info table and insert it in patient_info table as Foreign Key
I am getting this error :
In my localhost i can see the value it's suppose to return.
And this error which I suppose it occurs because i haven't inserted acc_id yet SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null
Also var_dump($data) returns array(1) { [0]=> object(stdClass)#3 (1) { ["acc_id"]=> int(124) } }
php file :
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$data = array();
try{
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
// Return data as JSON
echo json_encode($data);
var_dump($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:data, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
$stmt->bindParam(':data', $acc_id, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record was added to the database'));
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:
<?php
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$data = array();
try {
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
// You do not need to return response from here
// echo json_encode($data);
// var_dump($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
// the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
// notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
// so, I just added some dummy data.
$p_fname = 'Patient first name';
$p_lname = 'Patient last name';
$p_gender = 'm';
$p_condition = 'condition';
$p_birthdate = '1999-01-01';
$p_emergencycontact = 'Contact';
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
// You do not have any $acc_id variable in your code. To get data from your fetch you need to do
// like this:
$stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR);
$stmt->execute();
header('Access-Control-Allow-Origin: *');
// If you want to get the acc_id in your client side through the AJAX call, combine both
// mesage and data in the same JSON object.
echo json_encode(
array(
'message' => 'Congratulations the record was added to the database'
'data' => $data
)
);
} catch(PDOException $e) {
// make sure to send the proper status code
http_response_code(500);
// even error should be sent back as in json so that your javascript client can
// easily parse it
echo json_encode(
array(
'error' => $e->getMessage()
)
);
}
?>
I have the following PHP code:
$comp1 = $_POST['cohort_id1'];
$comp2 = $_POST['cohort_id2'];
$comp3 = $_POST['cohort_id1'];
$comp4 = $_POST['cohort_id2'];
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT cat_code, value, :comp1 , :comp2, round(:comp3/:comp4 * 100) as index_number FROM {$table}";
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) );
$stmt->execute(array(':comp1' => $comp1, ':comp2' => $comp2, ':comp3' => $comp3, ':comp4' => $comp4 ));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
Here is how one of the objects is returned:
?: "national_percent"
cat_code: "edu"
index_number: null
value: "Some College"
What I can't understand is why the first line returns with a "?", but more importantly, why the index_number is null. I suspect it is because those values are being converted into strings, but I'm not sure how to handle that.
To prevent SQL injection of user input that contains column names, check the input against an array of valid column names:
$valid_columns = array('col1', 'col2', 'col3');
if (in_array($user_input_col, $valid_columns))
{
$sql = "SELECT {$user_input_col} from table...";
...
}
else
{
die('Invalid column name');
}
I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>