mysql_fetch_array() problem - mysql

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?

Related

Laravel - How do update a table immediately records are saved in it

In my Laravel-5.8, I have this table.
CREATE TABLE `appraisal_goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then I created this controller to store record in another table.
public function store(StoreAppraisalGoalRequest $request)
{
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId; //$request->employees_id
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
}
As soon as the record is saved, I want to quickly query appraisal_goal_types
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
and update the record.
I need only one row there where the answer is true. I used the code above, but nothing is happening.
How do I resolve this?
Thank you
Try like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->parent_id = $parentid;
$goal->save();
There is an another solution like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
AppraisalGoal::where('id', $goal->id)->update(['parent_id' => $parentid]);
Both will works. And let me know if you solved the issue

What is fastest way to update multiple columns in a table from data of another table where updating table column(s) are something?

I have these two queries which work, but they are slow as can be. What is faster, or rather fastest way of doing this?
method 1)
$query = "
UPDATE list_data_extra
INNER JOIN list_data
ON (list_data_extra.serial_no = list_data.serial_no)
SET
list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0' AND list_data_extra.cid='0'
";
method 2)
$query = "UPDATE list_data_extra
INNER JOIN list_data USING (serial_no)
SET list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0'
AND list_data_extra.cid='0'";
Not sure this other method would be faster:
method 3)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query(
"SELECT id, cid, first, last, tracking_number
FROM list_data
WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$querythree = "UPDATE list_data_extra
SET id='".$querytwo["id"]."', cid='".$querytwo["cid"]."',
first='".$querytwo["first"]."', last='".$querytwo["last"]."',
tracking_number='".$querytwo["tracking_number"]."'";
mysql_query($querythree);
}
}
Another thing i tried is this, which is building entire query then executing it all at once, which is a bit faster than above, but still slow as junk. the above is like 9 minutes per 1000 records and this here below is like 5 minutes per 1000.
method 4)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$id_loop = "";
$cid_loop = "";
$first_loop = "";
$last_loop = "";
$trackingnumber_loop = "";
$listids = "";
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query("SELECT id, cid, first, last, tracking_number FROM list_data WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$id_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["id"]."' ";
$cid_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["cid"]."' ";
$first_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["first"]."' ";
$last_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["last"]."' ";
$trackingnumber_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["tracking_number"]."' ";
$listids .= ", ".$row['listid'];
}
$listidsb = substr($listids, 2);
$querythree = "UPDATE list_data_extra
SET
id = CASE listid
".$id_loop."
END,
cid = CASE listid
".$cid_loop."
END,
first = CASE listid
".$first_loop."
END,
last = CASE listid
".$last_loop."
END,
tracking_number = CASE listid
".$trackingnumber_loop."
END
WHERE listid IN (".$listidsb.")";
mysql_query($querythree) or die(mysql_error());
}
Is there a better and faster way to update multiple columns in many records in one table with data from another table?
CREATE TABLE list_data (
id int(11) NOT NULL AUTO_INCREMENT,
cid int(11) NOT NULL,
first varchar(255) NOT NULL,
last varchar(255) NOT NULL,
tracking_number varchar(255) NOT NULL,
serial_no varchar(9) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=555555 DEFAULT CHARSET=latin1
Unindexed JOIN and WHERE conditions can be slow, especially if they involve string data; try running these two (they make take a little time to run if the tables are large), and then trying your original query again.
ALTER TABLE list_data
ADD INDEX serial_idx (serial_no);
ALTER TABLE list_data_extra
ADD INDEX serial_idx (serial_no);

How to prevent null values to updating MySQL database

My update query is
"UPDATE registration SET `dob` = '".$theDate."' , pwd='".$_REQUEST['n_password']."', name='".$_REQUEST['n_name']."' where id='".$_SESSION['id']."' "
Problem is that it is not necessary that user update all fields so if it happens there are null values coming from form and it will replace earlier value in database.
I can update it one by one after checking if field value is not null but if there is any other way r tutorial please help me
I can update it one by one after checking if field value is not null
but if there is any other way r tutorial please help me
Don't issue an UPDATE query after you check each value, instead add that column to the query you're building, then execute just one UPDATE with only the columns that had values.
$dbh = new PDO('mysql:host=localhost;dbname=whatever', 'user', 'password');
$params = array();
$sql = "UPDATE REGISTRATION SET `dob` = ?";
$params[] = $theDate;
if (!empty($_REQUEST['n_password'])) {
$sql .= ", `pwd` = ?";
$params[] = $_REQUEST['n_password'];
}
if (!empty($_REQUEST['n_name'])) {
$sql .= ", `name` = ?";
$params[] = $_REQUEST['n_name'];
}
$sql .= " WHERE `id` = ?";
$params[] = $_SESSION['id'];
$stmt = $dbh->prepare($sql);
$stmt->execute($params);

Mysql query always returns empty value

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.

Mysql not inserting defined values

session_start();
if(!$_SESSION['user_id'])
{
$_SESSION['user_id'] = rand(1, 1000000);
include 'database_connect.php';
mysql_query('INSERT INTO product_views (user_session_id)
VALUES
('.$_SESSION['user_id'].')');
}
$productid = $_GET['name'];
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
My field modelNumber is set to null, and I am performing an Update via the last query.
Do you think that since the default value is null, it is therefore not allowing an insertion?
My table structure:
CREATE TABLE `product_views` (
`id` int(10) DEFAULT NULL,
`user_session_id` int(11) DEFAULT NULL,
`product_id` varchar(100) DEFAULT NULL,
`view_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`modelNumber` varchar(...
I'm confused:
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
Why are you looping through this result set if you're not even using $row?
Edit: I think this is what you're really trying to do:
session_start();
if(!$_SESSION['user_id'])
{
// Get the user ID
$_SESSION['user_id'] = rand(1, 1000000);
require_once('database_connect.php');
// Get the model number and escape it to prevent SQL injection
$model_number = mysql_real_escape_string($_GET['name']);
// Insert a row that associates the user_id with the model number
mysql_query("INSERT INTO product_views (user_session_id,modelNumber) VALUES('{$_SESSION['user_id']}', '$model_number')");
}