Spaces in text stored as underscore in MySQL - mysql

I am storing text in MySQL by sending a request to a url with a function.
The url is encoded with %20 as spaces which is all very well but when it is stored in MySQL the spaces are replaced with underscore _ .
This is a sentence -> This_is_a_sentence.
Is there a way of avoiding this issue?
This is the code:
function new_experiment_reply($thread_title = '', $raven_thread_id = '', $text = '', $forum_url = '', $raven_forum_id = '')
{
$email = $this->session->userdata('email');
$query = $this->db->query("SELECT id FROM fn_users WHERE email='" . $email . "'");
$fn_user_id = $query->first_row()->id;
$query = $this->db->query("SELECT username FROM forum_users WHERE fn_user_id='" . $fn_user_id . "' AND raven_forum_id='" . $raven_forum_id . "'");
$username = $query->first_row()->username;
$date = date("Y-m-d H:i");
$query = $this->db->query('INSERT INTO promo_replies(thread_title, raven_thread_id, text, forum_url, raven_forum_id, date, fn_user_id, username) VALUES("'. $thread_title .'", "'. $raven_thread_id .'", "'. $text .'", "'. $forum_url . '", "'. $raven_forum_id . '", "'. $date . '", "'. $fn_user_id . '", "'. $username . '") ');
}
The inserted value of variables (as they are seen in Fiddler and as they should be):
$thread_title= Facebook%20vs%20Google
$raven_thread_id = 123441
$text = This%20is%20a%20sentence
$forum_url = domain.com
$raven_forum_id = 32
After echoing the query I got the following results:
INSERT INTO promo_replies
(thread_title, raven_thread_id, text, forum_url, raven_forum_id, date, fn_user_id, username)
VALUES
("Facebook_vs_Google", "123441", "This_is_a_sentence", "domain_com", "32", "2012-09-06 06:04", "8", "usssaa")
I am prepared to get bashed regarding the code so no worries there.

Related

Values received from parsing remote HTML file using simple HTML DOM Parser are not getting stored into mysql database

I want to store some parsed data into mysql database. My code is given below:
<?php
include('mysql_connection.php');
include('simplehtmldom_1_5/simple_html_dom.php');
$site = "www.xyz.com/19326072316";
$html = file_get_html($site);
foreach($html->find('body') as $body)
{
foreach($body->find('a.url') as $e)
{
$title = $e->plaintext;
echo '<b>Title: </b>' . $title . '<br>';
}
foreach($body->find('a.category') as $cat)
{
$category = $cat->plaintext;
echo '<b>Category: </b>' . $category . '<br>';
}
preg_match('/(\w+)\.xyz\.com\/.+/', $site, $matches);
$city = $matches[1];
echo '<b>City: </b>' . $matches[1] . '<br>';
foreach($body->find('div.month') as $month){
$month = $month->plaintext;
echo '<b>Start and end month: </b>' . $month . '<br>';
}
foreach($body->find('div.date') as $date){
$date = $date->plaintext;
preg_match('/([0-9]{1,2})/', $date, $match_date);
$date = $match_date[0];
echo '<b>Start and end date: </b>' . $date . '<br>';
}
foreach($body->find('li.new_WatchIcon') as $time){
$time = $time->plaintext;
echo '<b>Time: </b>' . $time . '<br>';
}
foreach($body->find('li#new_locationIconIE7 div') as $address){
$address = $address->plaintext;
echo '<b>Address: </b>' . $address . '<br>';
}
foreach($body->find('span.description') as $description){
$description = $description->innertext;
echo '<b>description: </b>' . $description . '<br>';
}
$query = ("INSERT INTO articles (event_name, date_added, start_date, start_month, end_date, end_month, year, city, state, full_address, time, description, contact) VALUES('$title', now(), '$date', '$month', '$date', '$month', '2014', '$city', 'Karnatka', '$address', '$time', '$description', 'NULL')") or die(mysql_error());
$run_query = mysqli_query($query, $connection);
}
?>
When I was using mysql_query, nothing was happening but when I used mysqli_query then I got following error:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given
I know this question is already asked many times, but I tried most of the ways to solve this issue, but nothing worked for me!
You are using the wrong order of the parameters of mysqli_query(). Instead of your
$run_query = mysqli_query($query, $connection);
it should be
$run_query = mysqli_query($connection, $query);
It would be a great enhancement, if you would use a prepared statement with placeholders for your INSERT query:
// Prepare the statement before your outer foreach loop:
$query = "INSERT INTO articles (event_name, date_added, start_date, start_month, end_date, end_month, year, city, state, full_address, time, description, contact)
VALUES (?, now(), ?, ?, ?, ?, '2014', ?, 'Karnatka', ?, ?, ?, NULL)";
// instead of mysqli_query use in the loop
if ($stmt = mysqli_prepare($connection, $query) {
// your parameters are all of string type and you have 9
mysqli_stmt_bind_param(
$stmt,
'sssssssss',
$title, $date, $month, $date, $month, $city, $address, $description);
foreach($html->find('body') as $body) {
// Please take care, that you only can assign values to those variables
// and execute the insert at the end of your loop
mysqli_stmt_execute($stmt);
}
}
Remarks:
I thought the last parameter of your query would be the special value NULL and not the string 'NULL'.

mysql_fetch_array convert into mysqli_

Im trying to rewrite mysql_ into mysqli_, but got 2 errors
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
and
mysqli_num_rows() expects parameter 1 to be mysqli_result,
why? Ive fixed mysql_query("SELECT...) into mysqli_query($db, "SELECT..) and all others
<?php
ob_start();
session_start();
include('config/configuration.php');
if($_POST['Login'])
{
$UserName=$_POST['username'];
$Password=md5($_POST['password']);
$UserQuery=mysqli_query($db, "SELECT Id, UserName, FirstName, LastName, Level FROM users WHERE UserName='$UserName' AND Password='$Password' AND IsActive=1 and level >= 3");
$UserDetails=mysqli_fetch_array($UserQuery);
if(mysqli_num_rows($UserQuery))
{
$_SESSION['UserName'] = $UserDetails['UserName'] . ' (' . $UserDetails['FirstName'] . ' ' . $UserDetails['LastName'] . ')';
$_SESSION['UserId'] = $UserDetails['Id'];
$_SESSION['Level'] = $UserDetails['Level'];
mysqli_query("UPDATE users SET NumberOfLogin = NumberOfLogin + 1, LastLoginDate = NOW() WHERE Id = " . $_SESSION['UserId'] . " ");
Your query is failing.
Try this to see the issue:
if (!$UserQuery) {
echo "MySQLi Error: " . mysqli_error($con);
die();
}

Head busting MYSQL error 1064 What's Wrong with my Syntax? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I've been staring at this for a moment and think I'm not perceiving the obvious.
The resulting display is 1064 (mysql reference says it's a syntax error)
$query = "INSERT INTO members ( id , username , password , all , articles ) VALUES ( ";
$query .= "'' , " ;
$query .= $username . "' , '" ;
$query .= $password . "' , '" ;
$query .= $allVals . "' , ";
$query .= "'' );";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
I should note that $allVals is an encoded json object.
What's wrong with my query?
$query .= "'' , " ;
You miss here a single-quote.
$query .= "'' , '" ;
Should do the job.
I'd also consider to use prepared statements to better see where your syntax error may be; when you try to build your query like this, is will be probably more difficult to debug it.
$stmt = $con->prepare("INSERT INTO members ( id , username , password , all , articles ) VALUES ( '', ?, ?, ?, '')");
$stmt->bind_param("sss", $username, $password, $allVals);
$stmt->execute();
/* ... */
It looks like there is a single quote after $username, but not before:
$query = "INSERT INTO members ( id , username , password , all , articles ) VALUES ( ";
$query .= "'' , '" ; //missed the quote here
$query .= $username . "' , '" ;
$query .= $password . "' , '" ;
$query .= $allVals . "' , ";
$query .= "'' );";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
You must put common after every values.
$query = "INSERT INTO members ( id , username , password , all , articles ) VALUES ( ";
$query .= "'' , '" ;
$query .= $username . "','" ;
$query .= $password . "', '" ;
$query .= $allVals . "' ";
$query .= ")";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
If you aren't inserting data into id or articles columns, don't include them as part of your query statement:
$query = "INSERT INTO members ( username , password , all ) VALUES ( '";
$query .= $username . "' , '" ;
$query .= $password . "' , '" ;
$query .= $allVals . "' );";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
Additionally, you need to make sure your variables are properly escaped.
I like doing it this way:
$query .= "('' , '".$username . "' , '" .$password . "' , '".$allVals . "' ,'' )";
It also lends itself to things like inserting multiple rows :
$qvals[] = "('' , '".$username[1] . "' , '" .$password[1] . "' , '".$allVals[1] . "' ,'' )";
$qvals[] = "('' , '".$username[2] . "' , '" .$password[2] . "' , '".$allVals[2] . "' ,'' )";
$qvals[] = "('' , '".$username[3] . "' , '" .$password[3] . "' , '".$allVals[3] . "' ,'' )";
$query = "INSERT INTO members ( `id` , `username` , `password` , `all` , `articles` ) VALUES ".implode(',',$qvals);
You can double check the result by checking what echo $query; outputs.

MySQL Update Not Updating Certain Rows

Here is my double-minded query:
$Quest = "SELECT * FROM TOAWorkorders";
$FindTechResult = mysql_query($Quest, $cxn)
or die ('The easter bunny is watching you' . mysql_error());
while ($row = mysql_fetch_array($FindTechResult))
{
if (strpos($BBT, 0, 3) != 'Sys')
{
$IdNum = $row['IdNum'];
$BBT = $row['BBT'];
$BBTArray = explode("-", $BBT);
$TechNum = $BBTArray["0"];
$Title = $BBTArray["2"];
$Name = explode(" ", $BBTArray['1']);
$FirstName = $Name["0"];
$LastName = $Name["1"];
}
echo $TechNum . ' !! ' . $FirstName . ' !! ' . $LastName . ' !! ' . $Title . '<br>';
$Quest = "UPDATE TOAWorkorders SET TechNum = '$TechNum', FirstName = '$FirstName', LastName = '$LastName', Title = '$Title' WHERE IdNum = '$IdNum'";
$result = mysql_query($Quest, $cxn) or die(mysql_error());
}
Everything works for about 2/3s of the database. That leaves 33,000 rows that are not updated. I cannot find any difference between the data that works and the data that doesn't.
Since you're doing an UPDATE, and you say the rest of the code works (meaning, I hope, that you get 109,112 echo'ed results), it must be that the ID isn't being found (WHERE IdNum = '$IdNum').
Try preceding that command with "SELECT COUNT(*) from TOAWorkorders WHERE IdNum = '$IdNum'" and see if you get 33,000 zeros when the program runs. If you do, then you have missing IdNum values in your table.
If you don't, please provide details and I'll let you know.

mySQL breaks when adding a var

I'm attempting to modify a mySQL query (that works) to return a more specific result. I've added a variable to the statement so that it looks for jobID AND UserName. Adding the $userName to the statement breaks it.
I've included the code below with the three variations of the SQL statement for comparison. I'm sure it's something obvious - to everyone but me...
Thanks in advance!
DB
// get all applicants from a User
public function GetAllMyApplications($from=false, $to=false, $user_name)
{
global $db;
$applicants = array();
if ($from >= 0 && $to > 0)
{
$sql_limit = ' LIMIT ' . $from .', ' . $to;
}
else
{
$sql_limit = '';
}
$user_name = "Bob Bobberton"; // reset this var for testing
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' ORDER BY name ASC ' . $sql_limit; // This was the original SQL that worked
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = ' . $user_name . ' ORDER BY name ASC ' . $sql_limit; // Added "and" $user_name - it breaks
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = "Bob Bobberton" ORDER BY name ASC ' . $sql_limit; // Replace var with value "Bob Bobberton" and it works
$result = $db->query($sql);
while ($row = $result->fetch_assoc())
{
$applicants[] = array('id' => $row['id'],
'job_id' => $row['job_id'],
'name' => $row['name'],
'email_address' => $row['email_address'],
'message' => str_replace(array("\r\n", "\r", "\n"), "<br />", $row['message']),
'resume_path' => base64_encode($row['resume_path']),
'created_on' => $row['created_on'],
'ip' => $row['ip']);
}
if (isset($applicants))
{
return $applicants;
}else{
return("");
}
}
change this
' AND name = ' . $user_name . ' ORDER BY name ASC '
to
" AND name = '" . $user_name . "' ORDER BY name ASC "
and it will work
The solution provided by Satya is not enough. You should escape your inputs properly.
Assume your $username contains a " character. That will break your SQL statement. So you should use prepared statements or, at least, use the function mysql_real_string_escape().