Mysql query always returns empty value - mysql

This is my code:
$pass = mysql_query("SELECT `password` FROM acc WHERE account_id = '122' LIMIT 1;");
$p = mysql_fetch_object($pass);
$passwd = ( ( $p->password != "" ) ? $p->password : "empty" );
Then I'm doing echo $passwd; and it's always is retuning the "empty" string.
Of course the row with account_id 122 exists.
What is wrong with that?

Try this code:
$query = mysql_query("SELECT * FROM `acc` WHERE `account_id`='122'") or die(mysql_error());
while($data=mysql_fetch_object($query)){
$pass = $data->password;
}
echo $pass
You should now be able to acces all fields from that row including the password field.

what if you change
$passwd = ( ( $p->password != "" ) ? $p->password : "empty" );
to
$passwd = (empty($p->password)) ? $p->password : "empty" );

You don't need the semi-colon at the end of your query. Why do you have a limit 1? acc should be unique on account_id as having multiple passwords for the same account should be impossible.
$pass = mysql_query("SELECT `password` FROM acc WHERE account_id = '122'");
As #shawn pointed out if your account_id is indeed a number it's better not to rely on the implicit character to number conversion. Though it doesn't actually matter it's not good practice.

Related

MYSQL - Don't add to query if string is empty

I have a query that selects based on multiple things. For example, game_name is a string that can be empty if the user so chooses. Is there any way to not do the searching part for game_name if the input is "" but still look for the others?
$stmt = $connection->prepare("SELECT * FROM $config->tablename WHERE id = ? OR game_name = ? OR gamer_tag = ? LIMIT ?");
$stmt->bind_param("ssss", $request->id, $request->game_name, $request->gamer_tag, $request->limit);
You should do a little workaround to control it and when the user wants the field to be empty, you should control that and add to query something like this:
convert this
game_name = ?
into this
game_name = ? OR game_name = game_name
So this will make always to be true for that field.
EDIT:
Combining #Amado's solution and my proposal resolves in less IF statements (only my POV).
$MyWhere = "id = ? OR gamer_tag = ? OR game_name = ?"
if(game_name !="") $MyWhere = $MyWhere." OR game_name = game_name";
$stmt = $connection->prepare("SELECT * FROM $config->tablename WHERE ".$MyWhere." LIMIT ?");
$stmt->bind_param("ssss", $request->id, $request->gamer_tag, $request->game_name, $request->limit);
You can add a little checking before performing the query:
$MyWhere = "id = ? OR gamer_tag = ?"
if(game_name !="") $MyWhere = $MyWhere." Or game_name = ?";
$stmt = $connection->prepare("SELECT * FROM $config->tablename WHERE ".$MyWhere." LIMIT ?");
if(game_name !=""){
$stmt->bind_param("ssss", $request->id, $request->game_name, $request->gamer_tag, $request->limit);
}
else{
$stmt->bind_param("sss",$request->id,$request->gamer_tag, $request->limit);
}

how to delete huge mysql rows depending on not equal

the problem that its a huge amount the query would be like
DELETE FROM `members` WHERE `membership` = 'C' AND (`id` != '1' AND `id` !='2' AND ...... thousands of ids );
how I can do that ?
I did also WHERE id NOT IN ("1","2"); but also did not work
can I use loop or something like that
the IDs that I want to keep and do not delete comes from another table contains a field holds the user ID that I don't want to delete I used PHP script to help me to generate the SQL query
like
<?php
require_once("inc.php");
$realty_uids = $db->query("SELECT `uid` from `realty2` ORDER BY `uid`");
$r = $db->fetch_assoc($realty_uids);
while($r = $db->fetch_assoc($realty_uids)){
$array[] = $r['uid'];
}
$input = array_unique($array);
echo "DELETE from `members` WHERE `membership` = 'C' ";
foreach($input as $key => $value){
echo " AND `id` != '".$value."' <br>";
}
echo ";";
DELETE FROM `members` WHERE `membership` = 'C' AND NOT EXISTS (SELECT at.uid FROM `realty2` at WHERE at.uid = `members`.id);
This way worked good thanks for every one tried :)

mySql statement

I have a sql statement where I want to get all the entry with the category of "Game" but do not want to retrieve the record with the code of "A00001".
Below is my sql code but there is an error in the where clause.
$sql1 = "SELECT * FROM productItem WHERE productName = '$name' AND skuCode != '$mySKU';";
$mySKU = 'A00001';
$sql1 = "SELECT * FROM productItem WHERE productName = '$name' AND skuCode != '$mySKU'";
You have an extra ; lurking somewhere in there. Be sure to sanitize $mySKU if it is user input and use prepared statements.
update: Using PDO:
$stmt = $dbh->prepare("SELECT * FROM productItem WHERE productName = :name AND skuCode != :mySKU");
if ($stmt->execute(array('name' => $name, "mySKU" => $mySKU))) {
$rows = $stmt->fetchAll(); //if you are sure there are records
Try this:
"SELECT * FROM productItem WHERE productName = '$name' AND skuCode <> '$mySKU';";
Not equal statement is <>
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_not-equal

Check whether value exist in database

What's the best way to check whether the value is in the database?
Am I doing it correct?
$result = mysql_query("SELECT COUNT(*) FROM table WHERE name = 'John'");
$count = count($result);
you could use straight forward ,
mysql_num_rows() ;
eg :
$con = mysql_connect($host,$uname,$passwd)
mysql_select_db($dbase,$con);
$result = mysql_query($query,$con);// query : SELECT * FROM table WHERE name='jhon';
if( ! mysql_num_rows($result)) {
echo " Sorry no such value ";
}
Yes you are doing it right, if you are only concerned with checking if there are any records where name='john'
SELECT COUNT(*) FROM table WHERE name = 'John'
will return the no. of records where name field is 'John'. if there are no records then it will return 0, and if there are any records it will return the number of records.
But the above query will miss the entries where name is 'John Abraham' or 'V john', to include even these
you can modify your query like this.
SELECT COUNT(*) FROM table WHERE name like '%John%'
I'd say yes.
$result = mysql_query("SELECT COUNT(*) AS 'nb' FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['nb'];
Will give you the number of matching rows.
$result = mysql_query("SELECT COUNT(*) as user FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['user'];
if($count!=0)
{
echo "user exists";
}
else
{
echo "There is no such user";
}

mysql_fetch_array() problem

So I have 3 DB tables that are all identical in every way (data is different) except the name of the table. I did this so I could use one piece of code with a switch like so:
function disp_bestof($atts) {
extract(shortcode_atts(array(
'topic' => ''
), $atts));
$connect = mysql_connect("localhost","foo","bar");
if (!$connect) { die('Could not connect: ' . mysql_error()); }
switch ($topic) {
case "attorneys":
$bestof_query = "SELECT * FROM attorneys p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC";
$category_query = "SELECT * FROM categories";
$db = mysql_select_db('roanoke_BestOf_TopAttorneys');
$query = mysql_query($bestof_query);
$categoryQuery = mysql_query($category_query);
break;
case "physicians":
$bestof_query = "SELECT * FROM physicians p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC";
$category_query = "SELECT * FROM categories";
$db = mysql_select_db('roanoke_BestOf_TopDocs');
$query = mysql_query($bestof_query);
$categoryQuery = mysql_query($category_query);
break;
case "dining":
$bestof_query = "SELECT * FROM restaurants p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC";
$category_query = "SELECT * FROM categories";
$db = mysql_select_db('roanoke_BestOf_DiningAwards');
$query = mysql_query($bestof_query);
$categoryQuery = mysql_query($category_query);
break;
default:
$bestof_query = "switch on $best did not match required case(s)";
break;
}
$category = '';
while( $result = mysql_fetch_array($query) ) {
if( $result['category'] != $category ) {
$category = $result['category'];
//echo "<div class\"category\">";
$bestof_content .= "<h2>".$category."</h2>\n";
//echo "<ul>";
Now, this whole thing works PERFECT for the first two cases, but the third one "dining" breaks with this error:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource ... on line 78
Line 78 is the while() at the bottom. I have checked and double checked and can't figure what the problem is. Here's the DB structure for 'restaurants':
CREATE TABLE `restaurants` (
`id` int(10) NOT NULL auto_increment,
`restaurant` varchar(255) default NULL,
`address1` varchar(255) default NULL,
`address2` varchar(255) default NULL,
`city` varchar(255) default NULL,
`state` varchar(255) default NULL,
`zip` double default NULL,
`phone` double default NULL,
`URI` varchar(255) default NULL,
`neighborhood` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=249 DEFAULT CHARSET=utf8
Does anyone see what I'm doing wrong here? I'm passing "dining" to the function and as I said before, the first two cases in the switch work fine.
I'm sure it's something stupid...
You should always initialize the variable you use to some (null) value and then check for it before using it. My guess is that your third case (dining) never gets executed because of some misspelled identifier or something. This causes default: to run, after which your while() will execute anyway. However, $query is not set to anything useful.
Therefore, you should throw an exception or otherwise break execution in the default: handler. Or, you may initialize $query = null; before the switch() and only do the while() loop when $query !== null.
On a related note: you might code more efficient when you instead use the following (note the exception handler):
$db_name = null;
$table = null;
switch ($topic) {
case "attorneys":
$db_name = 'roanoke_BestOf_TopAttorneys';
$table = 'attorneys'
break;
case "physicians":
$db_name = 'roanoke_BestOf_TopDocs';
$table = 'physicians'
break;
case "dining":
$db_name = 'roanoke_BestOf_DiningAwards';
$table = 'restaurants'
break;
default:
throw new Exception("Unknown topic.");
break;
}
$bestof_query = "SELECT * FROM $table p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC";
$category_query = "SELECT * FROM categories";
$db = mysql_select_db($db_name);
$query = mysql_query($bestof_query);
$categoryQuery = mysql_query($category_query);
You're getting a sql error on that query. You should echo your mysql error and review it to fix your query. The warning you're getting is because you're passing a boolean false to mysql_fetch_assoc() which is expecting a result set. mysql_query() returns false if there is an error.
Look at your query code - you run $bestof_query regardless of whether it has been set to valid SQL. My first guess is that you're misspelling 'dining' somewhere and getting the default case.
Also, double check that your database names are correct (they are fairly complicated) and that all databases have the same permissions. Are you checking whether $db is true?