Is it possible to check to see if a variable is in a SQL Table?
For example if I wanted to check if "potato" is in the "veg" table?
$search = $_POST['search_input'] (potato)
You can do like this
Example
CREATE TABLE veg(veg_items CHAR(30));
INSERT INTO veg VALUES('potato'),('Redish'),('Ginger');
SELECT veg_items FROM veg WHERE veg_items = 'potato';
+-----------+
| veg_items |
+-----------+
| potato |
+-----------+
1 row in set (0.00 sec)
Using the mysql_ methods of PHP you can do it like this:
$sql = "SELECT COUNT(*) count FROM veg WHERE name = 'potato'";
$result = mysql_query($sql) or die('error');
$row = mysql_fetch_assoc($result);
if($row['num']) {
echo 'vegetable exists';
}
This is just to give you an idea how it works. If you want (and you should, because mysql_ is deprecated) to use PDO or mysqli the query remains the same.
PDO Example
$vegetable = 'potato';
$stmt = $conn->prepare('SELECT 1 FROM veg WHERE name = :name');
$stmt->bindParam(':name', $vegetable, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row) {
echo 'vegetable exists';
}
Use the potato at the WHERE clause:
Select * from veg where name='potato';
If you want to check the input of someone, use SELECT * FROM veg WHERE name='$search'
Beware of mysql injection though.
Try PDO Statements for such kind of queries .. because such queries are more prone to SQL injections.
try below
$sth = $dbh->prepare('SELECT count(*) FROM veg WHERE name =:name ');
$sth->execute(array('potato'));
$ret = $sth->fetchAll();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.