I am trying to verify in a field of a mysqli table if it is = an exact string.
That is:
$consulta = "SELECT count(*) as total FROM productos WHERE productos.stock = 'si' ";
Is it well formulated?
I am trying to verify in a field of a mysqli table if it is = an exact string.
That is:
$consulta = "SELECT count(*) as total FROM productos WHERE productos.stock = 'si' ";
Is it well formulated?
Depends on how your column is:
stock
is case insensitive (ci) The query:
SELECT count(*) as total FROM productos WHERE productos.stock = 'si'
It will count in the columns whose values are:
stock
is NOT case insensitive (ci) It will only count when the value is:
It will not even tell you if the value is: SI
or Si
or sI
.
We are going to do some tests with code.
COLLATE
with case insensitive (ci) in CREATE TABLE
: /*Ejemplo de case insensitive en el CREATE*/
CREATE TABLE IF NOT EXISTS tabla_ci_20180122
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
texto VARCHAR(25)
)COLLATE utf8_spanish_ci, ENGINE=INNODB;
INSERT INTO tabla_ci_20180122 (texto)
VALUES
('si'),('SI'),('sí'),('sï'),('no')
;
SELECT COUNT(*) total FROM tabla_ci_20180122 WHERE texto='si';
total
4
COLLATE
case sensitive (cs) in CREATE TABLE
The same previous data is used.
/*Ejemplo de cs en el CREATE*/
CREATE TABLE IF NOT EXISTS tabla_no_ci_20180122
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
texto VARCHAR(25)
)COLLATE latin1_general_cs, ENGINE=INNODB;
INSERT INTO tabla_no_ci_20180122 (texto)
VALUES
('si'),('SI'),('sí'),('sï'),('no')
;
SELECT COUNT(*) total FROM tabla_no_ci_20180122 WHERE texto='si';
total
1
COLLATE
of the table by default, and a column with cs
explicitly The COLLATE
can be set for the entire table, but some columns can have their own COLLATE
, different from the table.
/*Ejemplo de una tabla con COLLATE mixto: se establece una columna cs explícitamente*/
CREATE TABLE IF NOT EXISTS tabla_mixta_20180122
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
texto_ci VARCHAR(25),
texto_no_ci VARCHAR(25) COLLATE latin1_general_cs
) ENGINE=INNODB;
INSERT INTO tabla_mixta_20180122 (texto_ci, texto_no_ci)
VALUES
('si','si'),('SI','SI'),('sí','sí'),('sï','sï'),('no','no')
;
SELECT COUNT(*) mixta_ci FROM tabla_mixta_20180122 WHERE texto_ci='si';
Result:
mixta_ci
4
SELECT COUNT(*) mixta_no_ci FROM tabla_mixta_20180122 WHERE texto_no_ci='si';
Result:
mixta_no_ci
1