imported link from database cut off at UTF8 - php

I'm inserting data into my database as a string. The link column is latin1_swedish_ci. I tried changing it to UTF8_swedish_ci (that didn't help). I'm inserting a link and it gets inserted completely how it is. I'm passing this link to a php file which is a popup and then outputting it on the screen. During the output, if any of the links contain www.blahblah.com/somethingUTF8...there is more after UTF8 in the database but not on the screen. Sorry for the long explanation...here's the code:
Inserting into DB:
$xml = simplexml_load_file($feed);
foreach ($xml->channel->item as $list){
$stmt = $mysqli->prepare ("INSERT INTO some_db (title, am_desc, link) VALUES (?,?,?)");
$stmt->bind_param("sss", $title, $am_desc, $link);
$title = $list->title;
$am_desc = $list->description;
$link = mysqli_real_escape_string($mysqli, $list->link);
$stmt->execute();
$stmt->close();}
This is how I call the popup after running the mysqli_fetch_array to the the link:
<div style='position:relative; left:140px; padding-bottom:10px;
width:100px'><a href='popup.php?link=".$link."'
onClick='popup(this.href); return false;'>Click To Order</a></div>
And this is how I'm getting the code passed from the link in the popup:
$link = $_GET['link'];
It works for every link that does not have the UTF8. I'm pretty new at this and the solution might be simple but I haven't been able to find it for hours. Please help!

Try $link = utf8_encode($_GET['link']); .....that should do the trick ;)

Related

MySQL not using PHP variables properly in Queries, replacing the variables with strings/integers works fine

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.

PDO Insert Into DB

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();
?>

PHP Remove \ from a string that is pulled from DB

I built a blog that uses a WYSIWYG editor(TinyMCE). You build a blog post, post it, and it is stored in a MySQL Database. The post then gets pulled out by another page. Simple stuff for most of you I'm sure.
It worked fine on my test server, so I switched it to another server, and now the images don't pull through properly on the view blog page.
I inspected the img URL and it looked like this.
<img src="\"/img/parking1.png\"" alt="\"\"">
I haven't written a method to do it, but it seems to be escaping () the quote marks.
It didn't do this on my last server, and worked fine, so I am assuming it's a server (hosting) security thing.
I tried to remove them, replace them with blank:
$cleanpost = str_replace('\', '',$post);
Where $post is the data pulled from the DB. It's bad syntax and putting the back-slash in between the quotes breaks it.
Can anyone tell me how to do this please? Or am I even correct as to think this is what I should be doing?
Much thanks.
EDIT: PHP code for blog post insert
if (isset($_POST['blogpost'])) {
$nowdate = new DateTime('NOW');
$thisdate = $nowdate->format('Y-m-d H:i:s');
$post = $_POST['blogpost'];
$title = $_POST['posttitle'];
$status = 'yes';
try {
$conn = new PDO('mysql:host=host;dbname=dbname', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO blogposts(posttext, thisdate, posttitle, active) VALUES(:post, :postdate, :posttitle, :status)');
$stmt->execute(array(
':post'=>$post, ':postdate'=>$thisdate, ':posttitle'=>$title, ':status'=>$status
));
//echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
echo 'died';
};
}
You can use stripslashes() to unescape the string.
$post = stripslashes($post);
Try this
$cleanpost = str_replace('\"', '',$post);

storing source efficiently into sql escaping

Im having issues with storing source code into a db for a small script bin. The issue is that the printed code in the syntax highlighter used to view from the db has line breaks where it shouldnt, i have seen also in the db the text has stored in the same manner.
I have tried using severalk means to make this work, at first i thought was a wrap issue, so i set wrap to hard on the input form. Then added addslashes and that did not work, ive tried magic_quotes and in this case shown below ive tried mysql_real_escape_string and the text that comes from $content will store in the db with line breaks in places they shouldnt be.
Am i missing something? thanks
This code below is the insert into db and the value concerned is $content
<?php
session_start();
$submit = $_POST['submit'];
$sniptitle = ($_POST['sniptitle']);
$date = date("Y-m-d H:i:s");
$user = $_SESSION['username'];
$lang = ($_POST['lang']);
$con=mysqli_connect("localhost","xxxx","xxxx","xxxx");
$content = mysql_real_escape_string($_POST['snipcontent']);
// ^^^HERE IS THE ISSUE ^^^
if(isset($_POST['submit'])) {
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO code_lib ( snip_title , snip_content , posted_by , lang , datetime )
VALUES ('$sniptitle' , '$content' , '$user' , '$lang' , '$date' )");
mysqli_close($con);
header ("Location: xxx"); // Move back to a page
exit();
}
?>
mysql_real_escape_string shouldn't be used with mysqli by any means
thevertheless, it shouldn't be an issue either
most likely your "solution" is paired with stripslashes on fetch
So, the right solution would be
turning magic quotes off
and using mysqli_real_escape_string

output varchar with html tags from sql - output is encoded and should not be

Saving input from a form field into sql database varchar(255)... The input would be something like :
Author Name
Bottom line is it will more than likely have html tags in it most of the time. When I retrieve and output from the database I get something like :
<a href="test.com">Author Name</a>
As this should be echo'ed as html it does not show properly on the page. Maybe I am just tired, but I cannot figure out how to output this as non-encoded so it is properly read by the browser.
Try this:
<?php
echo htmlspecialchars_decode("<a href="test.com">Author Name</a>");
?>
Why do you encode the html tags before inserting into the database?
#Connect to the DB
$db = mysql_connect('localhost', 'root', '');
#Select the DB name
mysql_select_db('test');
#html tag contain in a string='$str'
$str='<a href="test'.'.com"'.'>Author Name</a>';
###insert query section ###
#Ask for UTF-8 encoding
mysql_query("SET NAMES 'utf8'");
#Set the Query
$sql = "INSERT INTO `test`.`code` (`name`) VALUES ('$str');";//Save it in a text row, that's it...
#Run the query
mysql_query($sql);
###fetching result###
#fetching required info from mysql
$sqlQuery1 = "SELECT * FROM `code` WHERE `name` LIKE '$str'";
$result1 = mysql_query($sqlQuery1); //order executes
$row1 = mysql_fetch_array($result1);
if( $row1){
echo $row1['name'] ;
}
#HOPE THIS HELP YOU ALOT

Categories