Checking if data exists in database - php

What is the right way of checking if the required data is in the database?
What I use currently is,
mysql_query("SELECT anyfield FROM table WHERE field='$data'");
and then check the if any rows are affected.
But I dont really have any use with the extracted data anyfield.
Eventhough the resource usage is so minor here, what is the right way to check if data exists in a db without extracting any other fields from the table?

Let the database count and retrieve the count data from the query.
$result = mysql_query('SELECT COUNT(*) FROM `table` WHERE `field` = ...');
if (!$result) {
die(mysql_error());
}
if (mysql_result($result, 0, 0) > 0) {
// some data matched
} else {
// no data matched
}

$result = mysql_query("SELECT `field` FROM `table` WHERE `field` = '".$data."'");
if (mysql_num_rows($result)){
// Rows exist
}
OR
$result = mysql_query("SELECT COUNT(`field`) as count FROM `table` WHERE `field` = '".$data."'");
$row = mysql_fetch_array($result);
if ($row ['count']){
// Rows exist
}

I would ensure, if I was checking for data, that as little data was returned as possible.
Fetch one field (I usually do id) and ensure you use LIMIT, eg. LIMIT 1... assuming you only want to know if any record exists.
Because you're using a PHP variable to find a record, if it suits your situation, you could perhaps do a LEFT JOIN on the first SQL line that gets $data, but that might just as easily be overkill for what you need.

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

Check information from another array

I have 2 tables in the database, the table circle and the table gossips.
The table circle has 3 columns: id, idfrom, idto.
The table gossips has id, userid, gossip.
My objectif is to echo all the gossips only if the userid of this gossip (idto) and the id of the pageuser(idfrom) are on the same row in the table circle.
I wrote this code,
$query = 'SELECT * FROM gossips ORDER BY id DESC';
$result = mysqli_query($cxn, $query)
or die("Couldn't execute query");
$querycircle = 'SELECT idfrom,idto FROM circle WHERE idfrom="{$pageuserid}" ';
$resultcircle = mysqli_query($cxn, $querycircle)
or die("Couldn't check if user in circle.");
while($row = mysqli_fetch_assoc($result))
{
while($rowcheck = mysqli_fetch_assoc($resultcircle))
{
if($row['userid'] == $rowcheck['idto'] || $row['userid'] == $_COOKIE['id']){
echo '<div class="gossip">'.$row['gossip'].'</div>';
}
}
}
But it doesn't seem to work properly.
Do you intend to get the same data with mysqli_fetch_assoc($resultcircle)) on each round of the first while-loop?
Then you should buffer this data in an array first, as executing mysqli_fetch_assoc will always give you the next data set on each successive call. It will not restart on top of the data.
(Btw, this is better: while(null !== ($rowcheck = mysqli_fetch_assoc($result))))
Another method to realize your objective is to do only one combined SQL request.
EDIT: Sudip Pal is fast, look at his answer for a combined request! ;)
Try the single SQL query for this and then try with one while loop.
Select A.gossip from gossips A, circle B where A.userid=B.idto and B.idfrom="{$pageuserid}" order by A.id DESC;
NOTE: you can also compare the COOKIE value by adding the extra comparison on the query, like and B.userid=$_COOKIE["id"] (better to save the cookie value in a variable)

Loop Through Records, Update one Record, and Exit

I want to select all records from my table and loop through all those records until I get to the record where the numtimespaid column is equal to 0. Once I find that column I want to update it to 2 for that record and then exit out. Here is what I have that is not working correctly:
$query1 = "SELECT * FROM ".$line." ORDER BY datestamp, timestamp";
$result1 = mysql_query($query1) or die(mysql_error());
while($row = mysql_fetch_array($result1)){
if ($row[numtimespaid] == 0) {
$queryupdate="UPDATE ".$line." SET numtimespaid=1";
$resultu=mysql_query($queryupdate);
break;
}
}
Any ideas as to what I'm doing wrong and/or the right way of doing this?
There is no need whatsoever to loop over rowset from a SELECT statement. You can simply update the first row with that value. This query will update exactly one record matching numtimespaid = 0. If you want to update all rows matching that criterion, just remove the LIMIT 1.
$result = mysql_query("UPDATE $line SET numtimespaid=1 WHERE numtimespaid = 0 ORDER BY datestamp, timestamp LIMIT 1");
By the way, we don't know what the contents of $line are, but hopefully you have properly filtered that value if it comes from user input. If it does comes from user input, it's recommended to check its value against a whitelist of possible table names:
// $line can be one of table1,table2,table3
if (!in_array($line, array('table1','table2','table3')) {
// FAIL, don't execute the query
}
if ($row[numtimespaid] == 0) {
Generally gets interpreted as numtimespaid being an undefined constant. Put quotes around it, like this:
if ($row['numtimespaid'] == 0) {
Then, realize Michael's answer is just better overall.

how to return array for mysql_query?

// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories