检查mysql中是否存在值 [英] Check if value exist in mysql
本文介绍了检查mysql中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小的脚本,用于从csv文件将数据上传到mysql数据库,并且我想检查csv文件内部的值列表.
I have a small script to upload data to mysql database from a csv file and I want to check the list of values that are inside of the csv file.
CSV文件:
code,alert_quantity
12345,10
PHP文件:
<?php
$link_id = mysql_connect("localhost", "root", "")
or die("Could not connect.");
if(!mysql_select_db("database",$link_id))
die("database was not selected.");
function _checkIfCodeExists($code){
$sql = "SELECT COUNT(*) AS count_no FROM products WHERE code = ?";
$count = $sql;
if($count > 0){
return true;
}else{
return false;
}
}
function _updateData($line_of_data){
$code = $line_of_data[0];
$newAlert = $line_of_data[1];
$sql = "UPDATE ";
}
$file_handle = fopen("file.csv", "r");
while (($line_of_data = fgetcsv($file_handle, 1000, ",")) !== FALSE) {
$query = mysql_query("SELECT * FROM products WHERE code ='$line_of_data[0]'") or die(mysql_error());
$message = '';
$count = 1;
if(_checkIfCodeExists($line_of_data[0])){
try{
_updateData($_data);
$message .= $count . '> Success:: Product with code (' . $line_of_data[1] . ') Exist (' . $line_of_data[0] . '). <br />';
}catch(Exception $e){
$message .= $count .'> Error:: While updating alert (' . $line_of_data[1] . ') of code (' . $line_of_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Error:: Product code (' . $line_of_data[0] . ') Doesnt exist<br />';
}
$count++;
}
echo $message;
?>
我不想导入此值,只是想检查是否存在并获取结果.
I don't want to import this values, just I want to check if exist and get the result.
感谢您的帮助.
推荐答案
正如其他人所说,您应该真正使用PDO.但是,要回答您的问题,mysql_num_rows是您的解决方案.
As others have said, you should really use PDO. But, to answer your question, mysql_num_rows is your solution.
$query = mysql_query("SELECT * FROM products WHERE code='$line_of_data[0]' AND alert_quantity = '$line_of_data[1]'") or die(mysql_error());
if (mysql_num_rows($query))
// Data is already in database
else
// Data not in database
这篇关于检查mysql中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文