I'm using PHP 5.4.31 and MySQL version 5.5.39-MariaDB. My database is in utf8_general_ci collation and some of my fields contain latin variants like á and é.
I am using the mysql:charset=utf8 directly in my PDO statement which works fine in Chrome and FireFox (on PC, Mac and tablet). But doesn't work in IE9.
If I use a URL such as "url_of_page.php?firstName=Joe&lastName=González" IE9 cannot find the record.
// get variables from URL
$fName = $_GET["firstName"] ;
$lName = $_GET["lastName"] ;
try {
$dbh = new PDO("mysql:charset=utf8;host=$hostname;dbname=databaseName", $username, $password);
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** The SQL SELECT statement ***/
$stmt = $dbh->prepare("SELECT * FROM Table WHERE FirstName = :firstName AND LastName = :lastName");
/*** bind the paramaters ***/
$stmt->bindParam(':firstName', $fName, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $lName, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$stmt->execute();
/*** fetch the results ***/
$result = $stmt->fetchAll();
foreach($result as $row) {
I've also tried using $stmt->execute("set names utf8"); which makes no difference. Don't understand why this is a browser issue. Any idea why IE is having problems?
The problem was that I had not used urlencode when assigning my URL variables and my URL was not in a valid ASCII format. After using urlencode my correct URL was something like:
url_of_page.php?firstName=Joe&lastName=Gonz%C3%A1lez
instead of
url_of_page.php?firstName=Joe&lastName=González
Related
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
i've read a lot of posts concerning similair problem with utf-8 issues and tried some too but i can't find the cause.
I'm using livecode and i want to encrypt some strings to a database. So i encrypt in Livecode then base64encode then send to database via PHP/PDO.
encrypt-->base64encode-->base64decode-->decrypt within livecode works ok.
Now when i send the base64encoded data to the MariaDB database it saves it, except + has become a space.
The database, table and columns are all utf8mb4_unicode_ci.
If i change the space to + manually via phpmyadmin in the database and read out with Livecode then it base64decodes-->decrypts correct!
This are the php files i use to connect and update the db:
<?php
// the connect.php file
$servername = "localhost";
$username = "blabla";
$password = "blabla";
try {
//$db = new PDO("mysql:host=$servername;dbname=blabla",$username, $password);
$db = new PDO("mysql:host=$servername;dbname=blabla;charset=utf8", $username, $password);
//$db = new PDO("mysql:host=$servername;dbname=blabla;charset=utf8mb4", $username, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'"));
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you can see i tried some charsets in the connect file also
<?php
//this is the file to update the DB
require_once 'connect.php';
//
try {
$stmt = $db->prepare("UPDATE tabel_users SET user=:user,
password=:password, email=:email, userlevel=:userlevel WHERE
id_user=:id_user");
$stmt->bindParam(':id_user', $_POST['id_user'], PDO::PARAM_INT);
$stmt->bindParam(':user', $_POST['user'], PDO::PARAM_STR);
$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':userlevel', $_POST['userlevel'], PDO::PARAM_STR);
//$stmt->bindParam(':user', $_POST['user'], PDO::PARAM_LOB);
//$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_LOB);
//$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_LOB);
//$stmt->bindParam(':userlevel', $_POST['userlevel'], PDO::PARAM_LOB);
$affected_rows = $stmt->rowCount();
if($stmt->execute()) { echo "Ge-update informatie verzonden naar de
database!"; } else { echo "Failure!"; };
}
catch(PDOException $e)
{
echo "Not updated: " . $e->getMessage();
}
//var_dump($_POST)
$db = NULL;
?>
Also tried PDO::PARAM_LOB
Tried VARCHAR VARBIN BLOB but this did not change a thing.
My first guess was that Livecode does something weird while posting it to the php file. But checking the variable just before it is send has the + in the string to send. So i don't really get it where it goes wrong.
Your issue is not with the database it is that php is url decoding your base64 string, that will convert '+' to ' ' (plus to space). You need to urlencode your password parameter before posting it. Here's the LiveCode doc for URLEncode.
It depends on the content type of your post as explained in more detail here.
I had the same problem but going from PHP to livecode and I got as far as concluding that the problem was with php encryption vs livecode encryption. if you try base encoding without encryption they will play nice. I don't have an answer for it though, but I remember the experts saying its got to do with the "header" of the encrypted binary. ideally i would like to see an answer to this problemnas I ended up going without encryption to get around it.
When I use base64 encoding to share data with another system (javascript)I always use this code after encoding:
Replace space with empty in tEncodedData.
LC adds spaces for base64encode. It works fine when I remove them.
I am starting to learn php PDO because I've read that it is more efficient and secure.
I could do the following with simple mysqli but am having trouble making it work with PDO.
PID stands for an id number.
fname stands for: first name.
lname stands for: last name.
age stands for ... age.
Basically I have an index.php that contains links from a test table called "persons" inside of the database drinks. When I click on the link which shows the fname of every row, it goes to insertcarbonated.php which is then supposed to $_GET['fname']; of the link and search up that specific row. However, my code in insertcarbonated.php is not working and I am not familiar enough with PDO to know exactly why, I would like some enlightenment on this because I literally begun learning PDO yesterday. :(
Here is my insertcarbonated.php:
<html>
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'theusername';
/*** mysql ***/
$password = 'thepass';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
/*** The SQL SELECT statement ***/
$fname = $_GET['fname'];
//is _GET even working with PDO?
$STH = $dbh-> prepare( "SELECT * FROM persons WHERE fname LIKE '$fname'" );
/***as Joachim suggested, I had actually two different variables here, however, it
did not solve the issue **EDITED** from ($DBH to $dbh)****/
$STH -> execute();
$result = $STH -> fetch(0);
//$result should print out the first column correct? which is the person's ID.
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<head>
</head>
<body>
<p><?php print $result; ?></p>
//me trying to print out person's ID number here.
</body>
</html>
As previously mentioned, I'm not sure where my error is, I get fatal error:
Call to a member function prepare() on a non-object?
and If I try to not use that function, my page is simply blank and nothing prints out.
Basically I would just like to print out different bits of information from that row (that is from it's relevant link in index.php). I would like to know how to solve this using PDO.
Here is the previous question I asked, and it was solved but not with PDO.
Previous question
You could do something like this...
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
$fname = $_GET['fname'];
$sth = $dbh->prepare("SELECT * FROM persons WHERE fname LIKE ?");
$sth->execute( array($fname) );
$result = $sth->fetch(PDO::FETCH_OBJ); // or try PDO::FETCH_ASSOC for an associative array
}
catch(PDOException $e)
{
die( $e->getMessage() );
}
In the HTML part you can do print_r($result) and you will see the exact structure of your results.
Comments: one of the best reasons to use PDO is the automatic escaping of the dynamic user inputs, like $fname here, so you should use it. Also, with $sth->fetch($param) the $param is not the column number but the type of the fetch method PDO will use (see PHP manual). Depending the method, you can get the PID of the result by $result->PID in case of PDO::FETCH_OBJ or by $result['PID'] when using PDO::FETCH_ASSOC. I hope this helps.
I've seen so many tutorials with so many different ways to insert using PDO. None of them seem to work for me. Can't seem to get mine to send to the database. I have no issue connecting and retreiving the data using FETCH but can't seem to post this data.
Any help with getting my post to work and redirect using the header or meta refresh would be nice. I am $_POST from an html form. Connecting to the db works just fine but can't get the data in.
$hostdb = 'myremoteip';
$namedb = 'cpdemo';
$userdb = 'root';
$passdb = 'mypassword';
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
if(isset($_POST['fname'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$title = $_POST['title'];
$photo = $_POST['photo'];
$stmt = "INSERT INTO row_users (fname,lname,title,photo)
VALUES (:first,:last,:title,:photo)";
$q = $conn->prepare($stmt);
$results = $q->execute(array(
":first"=>$fname,
":last"=>$lname,
":title"=>$title,
":photo"=>$photo
));
echo 'User Added<br/>';
}
header ('Location:../insertUser.html');
exit();
What you have to understand that there is no such thing like "PDO Insert Into DB"
There is INSERT query, irrelevant to PDO but regular to database you are using.
And there is PDO prepared statement, irrelevant to query type. You have to follow exactly the same pattern, no matter if it insert or delete.
So - all you need is just a tutorial on PDO prepared statements. That's all. Preferably one that teach you to enable error reporting in the first place.
As requested by OP, comment leading to an answer (to close the question and marked as solved).
I tested your code "as is", and it worked fine.
The only thing I can tell that could be the issue is, that your insert won't happen unless it meets the conditional statement you've set if(isset($_POST['fname']))
Check to see if your HTML form's elements are indeed named?
I.e. <input type="text" name="fname"> etc. If one of those are not not named or has a typo, then your whole query will fail.
You can try binding parameter before passing it to execute, like for example in the below code
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
is this code ok? because I don't get my db updated and I get no errors. Thank you.
//connect to db
$email = $mysqli->real_escape_string($_POST['email']);
$bo = $mysqli->real_escape_string($_POST['bo']);
$p1 = $mysqli->real_escape_string($_POST['p1']);
$p2 = $mysqli->real_escape_string($_POST['p2']);
$dt = $mysqli->real_escape_string($_POST['dt']);
$dt = new DateTime("2012-07-01 13:13:13", new DateTimeZone('Europe/Paris'));
//more validation code...
$stmt = $mysqli->prepare('UPDATE table SET Password=?, R_P=?, R_T=? WHERE E_mail=?')
$stmt->bind_param("ssss", $p2, $p2, $dt, $email);
$stmt->execute();
$stmt->close();
$mysqli->close();
//send email
I had no errors because I forgot to add on my page a thing that I always add on all my pages:
// check for errors
require_once('check_all_errors.php');
You encode the data twice, one manually and once by supplying them to a prepared statement. Just encode it once, like:
$stmt = $mysqli->prepare('UPDATE table SET Password=?');
$stmt->bind_param('s', $_POST['password']);
By the way, unless you truly want to write MySQL-specific code, there's no reason to use mysqli anymore. The PDO module supports multiple databases out of the box, with a similar interface.