I have a database which contains the following :
pnid partnumber desc code
==== ========== ==== ====
1 123-12345 hdd CMYK
So, the code field contains the pattern of the serial number I am looking for. What I would like to do is that I would like to fetch all the codes from my database, then check if a user input matches the code and display the part number of the matching code.
So saying that my input is ECMYK123456 then the function would return 123-12345.
I am really at lost. All I have is my basic PDO connection.
<?php
function checkPattern($inputString) {
$dbuser = "root";
$dbpass = "123456";
$dbconn = new PDO('mysql:host=localhost;dbname=3parsfdb',$dbuser,$dbpass);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $dbconn->query("SELECT * FROM `partnumber` WHERE '%$inputString%' LIKE `ctcode` LIMIT 1");
foreach ($query as $row) {
return $row['partnumber'];
}
}
echo checkPattern("ECMYK12345");
?>
When I try the function, it returns nothing. What is wrong with the code?
Final Code :
<?php
function checkPattern($inputString) {
$dbuser = "root";
$dbpass = "123456";
$dbconn = new PDO('mysql:host=localhost;dbname=3parsfdb',$dbuser,$dbpass);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $dbconn->query("SELECT * FROM `partnumber` WHERE '$inputString' like concat('%', ctcode, '%') LIMIT 1");
foreach ($query as $row) {
return $row['partnumber'];
}
}
echo checkPattern("ECMYK12345");
?>
Groan:
Note that it can’t use an index on code.