How do I convert a simple bit of MySQL to pdo - mysql

I know nothing about MySQL let alone PDO and am struggling to convert something to PDO.
I have tried everything I can by copying code from other bits of the script but can't get anything to work and knowing absolutely nothing about MySQL let alone PDO does not help in fact MySQL seems a heck of a lot easier to say the least.
I want is this very simple bit of MySQL to work as PDO.
$query = " UPDATE " . $DBPrefix . "settings SET
logo = '" . $_FILES['logo']['name'] . "' ";
$system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__);
$system->SETTINGS['logo'] = $_FILES['logo']['name'];

First you need to create new PDO() object. Something like this:
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO($dsn, $user, $pass, $opt);
Next your code will transform to:
$sql = "UPDATE {$DBPrefix}settings SET logo = '{$_FILES['logo']['name']}'";
$result = $pdo->query($sql);
But this is not a good practice to just write SQL manually, wrapping and escaping all params. Better way using prepared statements, it'll wrap and escape all params automatically:
$ps = $pdo->prepare("UPDATE {$DBPrefix}settings SET logo = :logo");
$ps->execute(['logo' => $_FILES['logo']['name']]);

you should put . after db prefix:
$query = " UPDATE " . $DBPrefix . ".settings SET
logo = '" . $_FILES['logo']['name'] . "' ";
$system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__);
$system->SETTINGS['logo'] = $_FILES['logo']['name'];

Related

Insert/Update MySQL into longtext Column

How do I insert the following string into MySQL:
$myValue ouputs: [Hey, this is a multi text file that has special characters like this ' and this '' and this ,,"", and this ''' and this '''' and this !#$ and whatever]
But the following will not work because of special characters:
$sql = "UPDATE `mytable` SET NEWS=('$myValue') WHERE _id='1'";
I do not want to manually escape every character (like adding an ' before every ')
Update/Insert should should start at [ and end at ] (as seen in $myValue)
EDIT (mysqli)
$_myValue = mysqli_real_escape_string($myValue);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `mytable` SET NEWS='$_myValue' WHERE _id='1'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
From the syntax of your code I assume that php is used to submit the queries to mysql.
If you just want to escape special characters in a string variable passed to a field, then use
PDO::quote() (if you use PDO)
mysqli_real_escape_string() (if you use mysqli)
mysql_real_escape_string() (if you use mysql, although you should not)
If you are looking for a more generic solution gainst sql injection, then consider using prepared statements. See this landmark SO topic on how to prevent SQL injection in php-mysql environment.
If your using php you could look at using PDO;
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE `mytable` SET NEWS=:myValue WHERE _id=1";
$st = $conn->prepare( $sql );
$st->bindValue(":myValue", $myValue, PDO::PARAM_STR);
$st->execute();
This will input all the data stored in $myValue. I would look at sanatising the input too.

Sql to JSON/XML [duplicate]

I am trying to export my MySQL tables from my database to a JSON file, so I can list them in an array.
I can create files with this code no problem:
$sql=mysql_query("select * from food_breakfast");
while($row=mysql_fetch_assoc($sql))
{
$ID=$row['ID'];
$Consumption=$row['Consumption'];
$Subline=$row['Subline'];
$Price=$row['Price'];
$visible=$row['visible'];
$posts[] = array('ID'=> $ID, 'Consumption'=> $Consumption, 'Subline'=> $Subline, 'Price'=> $Price, 'visible'=> $visible);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Now this reads a table and draws it's info from the fields inside it.
I would like to know if it is possible to make a JSON file with the names of the tables, so one level higher in the hierarchy.
I have part of the code:
$showtablequery = "
SHOW TABLES
FROM
[database]
LIKE
'%food_%'
";
$sql=mysql_query($showtablequery);
while($row=mysql_fetch_array($sql))
{
$tablename = $row[0];
$posts[] = array('tablename'=> $tablename);
}
$response['posts'] = $posts;
But now i am stuck in the last line where is says: $ID=$row['ID']; This relates to the info inside the Table and I do not know what to put here.
Also as you can see, I need to filter the Tables to only list the tables starting with food_ and drinks_
Any help is greatly appreciated:-)
There is no 'table id' in MySQL and therefore the result set from SHOW TABLES has no index id. The only index in the resultset is named 'Tables_in_DATABASENAME'.
Also you should use the mysqli library as the good old mysql library is depreacted. Having prepared an example:
<?php
$mysqli = new mysqli(
'yourserver',
'yourusername',
'yourpassword',
'yourdatabasename'
);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
. $mysqli->connect_error;
}
$result = $mysqli->query('SHOW TABLES FROM `yourdatabasename` LIKE \'%food_%\'');
if(!$result) {
die('Database error: ' . $mysqli->error);
}
$posts = array();
// use fetch_array instead of fetch_assoc as the column
while($row = $result->fetch_array()) {
$tablename = $row[0];
$posts []= array (
'tablename' => $tablename
);
}
var_dump($posts);

How to add insert into and log on pdo

I have an sql to add over 100 field to mysql database. I want to include coding for PDO to avoid this sql injection thing but, i'm new to all of this and really I do not know how nor truly understand it. Any help would be greatly appreciated. My form has over 100 fields. I have no knowledge of how to do this. Thank you in advance.
Here's the code.
<html>
<body>
<?php
>if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = array( "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state");
$sql_values=array();
foreach($mystuff as $fieldname) {
/* do validation! */
$sql_values[$fieldname] = "'" . mysql_real_excape_stiring($_POST[$fieldname]) . "'";
}
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname (".implode(',', $mystuff).") VALUES (" . implode(',', $sql_values) . ")";
mysql_query($sql,$con);
mysql_close($con);
}
foreach($mystuff as $fieldname) {
echo "...an input field...";
}
?>
</body>

I was looking to see if someone could tell me how secure this is

I am writing a code that will check 2 different tables to determine the privileges the user will have. The code looks like this:
$query1 = ("SELECT 1 FROM `customers` WHERE `Email` = '$email' AND `Password` = '$password'");
$query2 = ("SELECT 1 FROM `admins` WHERE `Email` = '$email' AND `Password` = '$password'");
$result1 = mysql_query($query1) or die(mysql_error());
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result1) == 1) {
// Log user in as a Customer
exit;
} else if (mysql_num_rows($result2) == 1) {
// Log user in as an Admin.
exit;
} else {
// Direct user to registration page.
}
Can anyone look at this and tell me if there would be any security risk by doing it this way? Thank you in advance for your help!
Firstly you have a change that your code is only known by you.
Secondly you have to check the input data. email and password area is not safety. You should prevent SQL injection. Otherwise your code is not secure.
By the way i'm offering you IP restricted login for admins. I'm using this. And it is more secure.
One big problem here is that the code is vulnerable for sql injections.
Which basicly means that the user could put code in the email or password form to bypass the check you have here.
A start would be to perform the following to your input BEFORE you use them in your query:
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
Though, the mysql library is not recommended by php, rather read about prepared statements in pdo here: http://www.php.net/manual/en/ref.pdo-mysql.php
But you can try the mysql_real_escape_string to have a first security measure against sql injections.
This is insecure if for example my password was
OR 1=1
I get access. Use mysql prepared statements
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("SELECT 1 FROM customers WHERE Email = (?) AND Password = (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ss", $email, $password)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>

how to bind values INSERT INTO mysql perl

I've got the code below that works but I need to know how to bind them for security. If I just replace $new_row with ? and put it in execute I get an error. Thanks for your help.
foreach my $field (#account_field_order) {
$new_row .= "'" . param($field) . "', ";
}#foreach
$new_row .= "'$status'";
my $dsn = "DBI:mysql:$database";
my $dbh = DBI->connect($dsn, $MYSQLuserid, $MYSQLpassword )
or die $DBI::errstr;
my $sth = $dbh->prepare(qq(INSERT INTO $table VALUES ($new_row) )) or die $DBI::errstr;
$sth->execute() or die $DBI::errstr;
You will want to use placeholders, and never interpolate variables in strings. You should probably use taint mode and de-taint your param values before using them, if safety is important to you. Documentation on placeholders here.
Try something like:
my #values = map param($_), #account_field_order; # add values to array
push #values, $status; # for simplicity
$new_row = join ", ", ("?") x #values; # add ? for each value
... # basically same code as before, except the execute statement:
$sth->execute(#values); # arguments given will be inserted at placeholders
If your values were in a hash, there's the insert_hash example in the docs (under prepare_cached). Adjust as appropriate if not using an array.