mysql cyrillic troubleshooting - php

Hi guys!
So, I have one question: I have some data which is cyrillic. Here is the problem:
Incorrect string value: '\xD0\xBD\xD0\xBE\xD0\xB2...' for column 'title' at row 1.
Here is my code:
$link = mysql_connect('localhost', 'root', 'pass');
if($link&&isset($_POST['addSticker'])){
$title = $_POST['title'];
$description = $_POST['description'];
$photo = mysql_real_escape_string(urlencode($_POST['photo']));
$quantity = $_POST['quantity'];
$price = $_POST['price'];
mysql_select_db('db_name');
$sql = "INSERT INTO table (title, description, photo, quantity, price) VALUES ('$title', '$description', '$photo', '$quantity', '$price');";
mysql_query("SET NAMES utf8", $link);
mysql_query($sql, $link) or die(mysql_error());
}
Thanks for any help.

First thing is that your query is vulnarable to SQL injections. It is recommended to escape your characters (MySQLi). This might even solve your problem. The second thing is you're still using mysql API which is deprecated. Instead, you should switch to PDO or mysqli API. In case you have bad collation (escaping input doesn't help), you can also change MySQL collation to one of these so that database can understand these characters.

Related

Inserting latin chars in mysql using php?

I have a database that contains latin chars like á, é, ç etc. I can insert tuples with those chars using the MySQL admin interface by writing the SQL insert statements there. I can also read and display them without any problem. But I can't insert new data properly using PHP.
$mysqli = new mysqli("localhost", "root", "", "budgets");
$data = mysqli_real_escape_string($mysqli, "bananá");
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
I have read several threads suggesting to use mysqli_real_escape_string(), and making sure the charsets were configured properly, but nothing worked.
I tried using different charsets in the database but the á is always replaced by strange symbols. Currently I'm using utf8_general_ci as the charset of the database.
Thank you in advance for any assistance.
First thing setup your table rows collcation to utf8_unicode_c
And add $mysqli->set_charset("utf8"); to your connection code
Finaly your code should look like this :
$mysqli = mysqli_connect(HOST_NAME,DB_USER,DB_PASS,DB_NAME);
if($mysqli === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$mysqli->set_charset("utf8");
$data = "bananá";
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->close();
$mysqli->close();

Mysql update function

I have created a form that submits to the mysql database. Now what I am trying to do is get it to update. The bit I'm having trouble with is the update query below, I just can not figure out where I am going wrong.
<?php
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
include 'db.php';
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$title = mysqli_real_escape_string($link, $_POST['title']);
$price = mysqli_real_escape_string($link, $_POST['price']);
$sqm = mysqli_real_escape_string($link, $_POST['sqm']);
$sqm_land = mysqli_real_escape_string($link, $_POST['sqm_land']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$area = mysqli_real_escape_string($link, $_POST['area']);
$location = mysqli_real_escape_string($link, $_POST['location']);
$bedroom = mysqli_real_escape_string($link, $_POST['bedroom']);
$terrace = mysqli_real_escape_string($link, $_POST['terrace']);
$orientation = mysqli_real_escape_string($link, $_POST['orientation']);
$water = mysqli_real_escape_string($link, $_POST['water']);
$seaview = mysqli_real_escape_string($link, $_POST['seaview']);
$pool = mysqli_real_escape_string($link, $_POST['pool']);
$ownerinfo = mysqli_real_escape_string($link, $_POST['ownerinfo']);
$gaddress = mysqli_real_escape_string($link, $_POST['gaddress']);
$description = mysqli_real_escape_string($link, $_POST['description']);
// attempt insert query execution
$sql = "update INTO property (title, price, sqm, sqm_land, type, area, location, bedroom, terrace, orientation, water, seaview, pool, ownerinfo, gaddress, description) VALUES
('$title', '$price', '$sqm', '$sqm_land', '$type', '$area', '$location', '$bedroom', '$terrace', '$orientation', '$water', '$seaview', '$pool', '$ownerinfo', '$gaddress', '$description' )";
if(mysqli_query($link, $sql)){
echo "Records updated successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
You're using the wrong syntax for UPDATE.
Read the manual:
http://dev.mysql.com/doc/en/update.html
What you're using is INSERT syntax. http://dev.mysql.com/doc/en/insert.html
Example from the manual:
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
and use a WHERE clause, otherwise you will be updating your entire db.
Example from the manual:
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;
So in your case and for example (fill in the rest):
UPDATE property SET title = '$title', price = '$price' ... WHERE column = ?
column being the column name you want to target and the ? being the row.
Your mysqli_error($link) would have thrown you something about it.
Sidenote: "Teach a person how to fish, rather than throwing them a fish".
However, if the goal here is to INSERT, then you need to use INSERT INTO table and not UPDATE INTO table.
Also make sure your form uses a POST method and that all POST arrays contain values.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Footnotes:
The MySQL API used to connect with in db.php is unknown. Make sure you are using the same API you are using to query with, being mysqli_. Different APIs do not intermix.
Your syntax is incorrect, it should be formatted like this:
$sql = "UPDATE property SET title='$title'";
You'll have to add all the name/value pairs separated by commas since I only included 'title.'

SQL - Insert INTO results in nothing

I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT

MySQL - PHP form to insert values into table?

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);

PHP form will not post

I have just implemented mysql_real_escape_string() and now my script won't write to the DB. Everything worked fine before adding mysql_real_escape_string():
Any ideas??
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
mysql_send("INSERT INTO list
SET id = '',
name = '$name',
description = '$description',
custid = '$custid' ");
what is that mysql_send function?
what if to change it to mysql_query();
It should be easy to figure out what's going on.
Fist, instead of sending the query you're constructing to the database, echo it out (or log it), and see what you're actually sending to the database.
If that doesn't make it obvious, see what mysql_error() has to say.
mysql_real_escape_string should have a database connection passed as the second argument since it asks the database what characters need to be escaped.
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
$cleanstring = mysql_real_escape_string("my string", $connection);
A typical failure on understanding how to use certain functions...
You're just using mysql_real_escape_string on raw input data. Have you ever heard of santizing / validating input? mysql_real_escape_string does not make sense on numbers. If you've validated a variable to be a number, you don't need to escape it.
mysql_send is an alias for mysql_query right?
Use debug code, add echo mysql_error(); after mysql_send(...).
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
//If you doing Update use this code
mysql_query("UPDATE list SET id = '', name = '$name', description = '$description' WHERE custid = '$custid' ") or die(mysql_error());
//OR if you doing Insert use this code.
mysql_query("INSERT INTO list(name, description, custid) VALUES('$name', '$description', '$custid')") or die(mysql_error());
//If custid is Integer type user $custid instead of '$custid'.
If you are updating the records in the list table based on the custid use the UPDATE command OR if you are insertinf the records into list table use INSERT command.

Categories