UPDATE mariaDB Query issues - php

got a permanent 1064 error with this query on mariaDB:
UPDATE field_news
SET friendly_url = REPLACE (friendly_url, ' ', '-')
WHERE id_news = $idNews;
The $idNews variable is well-set.
I broke my brains trying to find why mariaDB rejects the query.
If someone can bring me some light on this.
Regards.

You seem to be doing this update from you PHP code. You could make the quick fix of putting single quotes around $idNews. But instead, you should ideally be using a prepared statement here:
UPDATE field_news
SET friendly_url = REPLACE (friendly_url, ' ', '-')
WHERE id_news = ?;
To the ? placeholder, you would bind the actual PHP variable $idNews. Your PHP code might then look something like this:
$sql = "UPDATE field_news
SET friendly_url = REPLACE (friendly_url, ' ', '-')
WHERE id_news = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $idNews);
$stmt->execute();
$stmt->close();
Note one of the advantages of prepared statements is that they handle worrying about how to bind variables to your query.

Related

Error with mysql statement

I'm trying to blind my MySql query I noob in this, I want prevent to SQL Injection on my query. This is my statement but have one error
$sql = $conn ->prepare("SELECT * FROM Personas WHERE concat(nombre1,' ',apellido1) LIKE '% :name %'");
$sql-> bind_param('name', $q);
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match
number of parameters in prepared statement in
this work fine but that is a bad way
$sql="SELECT * FROM Personas WHERE concat(nombre1,' ',apellido1) LIKE '%".$q."%';
Please help me with this and what other way Can I use to protect my query in my PHP Code
Thank you for all, that was my solution
$sql = $conn ->prepare('SELECT * FROM Personas WHERE concat(nombre1," ",apellido1) LIKE ? ');
$key = "%".$q."%";
$sql-> bind_param('s', $key);
Use bind_param this way:
$sql= $conn->prepare("SELECT * FROM Personas WHERE concat(nombre1,' ',apellido1) LIKE :name");
$q= "%$q%";
$sql->bindParam(':name', $q);
$sql->execute();
The mysql documentation uses question marks (?) to indicate where a subsequent bind_param value should be placed. Try replacing ":name" with the a "?" in the query and your bind_param should follow the syntax bind_param("s", $q) where "s" is a string identifying the types of values being bound: s for string, d for decimal, i for integer, etc.

PDO query not displaying results?

Okay so i am new to PDO statements so i am unsure if i have done a syntax error or whatnot. The php file does not show any errors:
<?php
include('db_config.php');
$itemName = 'Item1';
$sql = "SELECT * FROM order WHERE itemName = $itemName;";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['itemName'];
}
?>
My objective is to pull an item using bootstraps datepicker, but for the purpose of this testing i am using the itemName.
The php file comes up blank?
I have checked the field names, db_config, and am unsure where the issue is coming from.
Please let me know if i have done an error in my statement or anything that seems wrong.
Firstly, you're using a MySQL reserved word, being order and it requires special attention; mainly using ticks around it.
Then since we're dealing with a string, $itemName needs to be wrapped in quotes.
<?php
include('db_config.php');
$itemName = 'Item1';
$sql = "SELECT * FROM `order` WHERE itemName = '$itemName';";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['itemName'];
}
?>
Either use ticks around your table name, or rename it to "orders", it's not a reserved keyword.
"The php file does not show any errors:"
That's because you're not checking for them.
Add $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); right after the connection is opened.
Now, if you're going to use PDO, use PDO with prepared statements, they're much safer.
As per a comment you left under your question containing the MySQL error:
1064 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 'order
Read it near 'order it starts at "order".
Now, if ever your query should ever contain any character that MySQL will complain about, such as a quote etc. then you will need to escape your query and use prepared statements.
For example, if using:
$itemName = "Timmy's Sour Dough";
would translate to
WHERE itemName = 'Timmy's Sour Dough'
in turn throwing a syntax error.
So, it's best to immediately escape any data right away.
Edit
Your use of prepare and new to PDO collectively suggest that you are already trying to use prepared statements, just not the right way. You're just a little off from a well prepared statement. One correct way in your code would be
$sql = "SELECT * FROM `order` WHERE itemName = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute(array($itemName));
Notice how we have a ? in your query then we are sending a value for it in your execute call. There you go :)
Using PDO with prepared statements will take care of that.
You're completely ignoring the main reason people use PDO. Prepared statements are what you should be using, which would make your query look like this:
$itemName = 'Item1';
$sql = "SELECT * FROM order WHERE itemName = ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $item, PDO::PARAM_STR);
$stmt->execute();
Read up on bindParam().
In future, turn on your error reporting at the beginning of the script with this:
ini_set('display_errors', 1);
error_reporting(E_ALL);
That will save you a lot of time.
Looks like there is an error in you sql statement. since itemName is either a varchar or text in your database, you need to put it in single quotes in the query:
$sql = "SELECT * FROM order WHERE itemName = '$itemName';";

Insertion query in sql php function

i'am beginner in php and i have problem in insertion query
if(isset($id)){
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') ";
$result = mysql_query($qry);
}
I'am connected to the database but the query didn't work.
Why it is not working? how can i correct it?
Don't create queries this way. It is very vulnerable to SQL injection.
Use a prepared statement instead. A prepared statement is precompiled, hence will not be subject to SQL injection.
$id = 99;
$tax = 8;
$stmt = $mysqli->prepare("insert into user_to_birds(user_id,tax_id)values(?,?)"));
$stmt->bind_param("ii", $user, $tax);
$stmt->execute();
.. work on it ..
$stmt->close();
ii stands for two integers. After that first part of the binding, telling which type of variables you use in which order, can you add the values of those variables to the statement. The values will be escaped automatically using this method.
if(isset($id)){
$qry = "insert into user_to_birds(user_id, tax_id)values('1','$id') ";
$result = mysql_query($qry);
}
Work like a charm.
I think your single quotes should be double quotes:
$qry = "insert into user_to_birds(user_id,tax_id )values( 1 ,".$id .") ";
You are confusing strings in PHP with strings in SQL (which is, admittedly, easy to do).
For how to insert into there's a nice article here
http://www.w3schools.com/php/php_mysql_insert.asp
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
//not sure if this will make a difference buy i would try a space between tax_id) and values(
also, im not sure if the way youve done it is wrong but i would have written like this
if(isset($id))
{
$qry = "insert into user_to_birds (user_id, tax_id)
values( '1' ,'".$id ."') ";
$result = mysql_query($qry);
}
look at string concatination aswell either have
" ' ' ".$variable." ' ' ";
in that fashion
As others have said, it looks like you're not using string concatenation correctly in your query. Try changing your query to something like:
$qry = "INSERT INTO user_to_birds (user_id,tax_id) VALUES ( 1 ,'$id') ";
Another possibility is that your $id variable isn't set. Try printing out the variale before doing the isset() check and that will tell you if you need to look at an earlier point in your code.
Finally, I'd recommend you look at mysqli functions rather than mysql.
http://php.net/manual/en/book.mysqli.php
You have some confusion in quotes: your string in " ", your sql value in ' ', but when you concatenate you need to close your string and write dot and variable, after this you need write dot, open string quotes again and write text if it needed. Your mistake - you didn't close string (") before concatenation and this leads to misinterpretation of the code. In this case your code will look like:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'" .$id ."') ";
But you can not use concatenation,you can do it simply: PHP allows write your variable $id in string, without use concatenation:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'$id') ";

PHP "SHOW TABLES" MySQLi query not working

i'm trying to execute a prepared statement with php but it doesn't work. My prepared statement is like:
SHOW TABLES LIKE "italy_turin_mathematics"
and i do it like this:
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?_?_?")) {
$stmt->bind_param('sss', "italy", "turin", "mathematics");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
I'm sure it must return something, because with PHPMyAdmin it does, but with PHP it always skips the while loop, i think there is something wrong with the prepared statement query, maybe it needs to escape the underscore char?
How can i do it?
Your database architecture is utterly wrong.
There should be only one table contains all the data, for all the places and sciences.
And you have to query it usual way, without employing SHOW TABLES at all.
So, it have to be something like
$sql = "SELECT * FROM t WHERE country=? AND city=? and science=?";
$stm = $pdo->prepare($sql);
$stm->execute(array("italy", "turin", "mathematics"));
$data = $stm->fetchAll();
the above code is in PDO, as you have to use it instead of mysqli.
Splitting tables is a very bad idea, violating the very fundamental rules of relational databases. As you can see, it makes you to run such a strange query and will make your further code even worse.
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?")) {
$country = "italy";
$city = "turin";
$course = "mathematics";
$stmt->bind_param('s', $country . "_" . $city . "_" . $course);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
As far as I know the code you had would result in a query looking as follows:
SHOW TABLES LIKE 'italy'_'turin'_'mathematics'
You cannot concatenate like that in mySQL, or any form of SQL I can think of.
SHOW TABLES LIKE ?_?_?
Should be:
SHOW TABLES LIKE CONCAT(?, '_', ?, '_', ?) --this gives an error, see below
And I fully agree with #your-common-sense's commentary that this is a terrible way to design a database and you will come to regret it in more ways than just this one messed up query.
edit:
MySQL does not seem to allow functions in a SHOW TABLES statement, so either you'll have to concatenate the table name to a single string in PHP, or you can use a query like:
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
table_schema = 'mydb' AND
table_name LIKE CONCAT(?, '_', ?, '_', ?);

Parameterised IN Clause in prepared statement using MySql,PHP and ADODB

I am writing some SQL and using AdoDb to connect to my database and run the queries and so on. I am using parametrized queries and have run into a snag.
Is their a way to pass an array of values to an in_clause in AdoDb/MySql for parametrization.
My problem is that if I pass a prepared string as the parameter i.e. 'test','test2','test3' it does not work as the library or database auto escapes it and adds external quotes at the start and end so all the internal quotes are then auto escaped thus the query returns nothing as it looks for '\'test\',\'test2\',\'test3\'' as opposed to what I fed it.
UPDATED WITH ANOTHER POSSIBLE METHOD TO ACCOMPLISH THIS
<?php
$in_clause = implode(",", $first_names);
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
FIND_IN_SET(mytable_fname," . $DB->Param('first_names') . ")"
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,array($in_clause));
?>
I would do it this way (as I was googling for a while and google came up with nothing useful):
$count = count($first_names);
$in_params = trim(str_repeat('?, ', $count), ', ');
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
mytable_fname IN ({$in_params});";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt, $first_names);
This should do it...
First a few tips:
Please read carefully the AdoDB documentation on prepared statements.
Never include ; in SQL query strings.
You can try something like this:
$question_marks = substr(str_repeat('?,', count($first_names)), 0, -1);
$query = "SELECT mytable_id_pk FROM mytable WHERE mytable_fname IN (" . $question_marks . ")";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,$first_names);
WARNING: I haven't tested this (not having a mySQL installation here).

Categories