简体   繁体   中英

correct way to check if a record exists in (mysql) table

To simply verify if a record exists in the table.
would this be the most optimal correct method ?

( if i were to also return an integer 1 or 0 )

char *qu;
qu = malloc(300);

sprintf(qu, "select 1 from account where un='%s' and pw='%s' limit 1",u,p);
mysql_query(co, qu);

res =  mysql_use_result(co);
row = mysql_fetch_row(res);

if(row){
return "exists";
}else{
return "no";
}

i also tried row[0] , that will cause problems when there is no records found. ( or perhaps even when found )..

The canonical way of doing this is:

SELECT EXISTS(SELECT * FROM account WHERE un=? and pw=?)

Note that I've used bind variables. You should always use them to parameterise your query for safety from SQL injection, rather than using sprintf .

References:

13.2.10.6 Subqueries with EXISTS or NOT EXISTS

27.8.9 C API Prepared Statement Data Structures

have you tried something like this:

while( row = mysql_fetch_row( res ) ) return atoi( row[ 0 ]); 
return 0; // or "no"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM