SQL SELECT with table name in query - mysql

I have simple query:
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT DATE(date_time) AS day_h
FROM `$table_name`
");
and it is working ok.
But I must do this query with table name and when I try this:
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT `$table_name`.DATE(date_time) AS day_h
FROM `$table_name`
");
or
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT v_c_holi_2012.DATE(date_time) AS day_h
FROM `$table_name`
");
this is not working (Fatal error: Call to a member function fetch_assoc() on a non-object).
What I 'm doing wrong?

The date function should not have the table prefix since it is a system function.
Instead you need to put the table alias before your field date($table_name.date_time).
By the way, you don't need to if you select from only one table.

I believe $table_name.DATE(date_time) should be DATE($table_name.date_time)

You should apply the table name to the thing that's in the table (i.e. the field name), not the DATE function (which has nothing to do with your table).
i.e.
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query(
"SELECT DATE(`$table_name`.`date_time`) AS `day_h`
FROM `$table_name`"
);

Related

What's wrong with this SQL query WHERE AND clause?

Previously, this was working:
$patient_story_set_photos = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patientID = '.$post->ID.' AND patient_display = 1');
However, when I try to add another AND condition like this:
$patient_story_set_photos = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patientID = '.$post->ID.' AND patient_display = 1 AND period_taken = '.$set->period_taken);
I get the following error on screen:
WordPress database error: [Unknown column '1hour' in 'where clause']
SELECT * FROM wp_before_after WHERE patientID = 8175 AND patient_display = 1 AND period_taken = 1hour
Can't see why there's a problem, are you not allowed to use multiple AND conditions in SQL?
The problem is not the AND, the problem is your 1hour, 1hour unquoted means a reference to an object (database, table) named 1hour, you need to quote '1hour'.
If you write
SELECT * FROM wp_before_after
WHERE patientID = 8175
AND patient_display = 1
AND period_taken = '1hour'
you will compare the field periodtaken to a string (CHAR,VARCHAR,TEXT) equal to '1hour'.
I assume period_taken is a field typed CHAR,VARCHAR or TEXT
Before anything, DO NOT CONCATENATE SQL STRINGS nowadays it is a MUST (see how to do it properly https://stackoverflow.com/a/60496/3771219)
The problem you are facing is because, I presume, that the period_taken field is some sort of Char/Varchar/String field and when you are filtering by a "Stringy" field you must sorround your literals values with single quotes:
SELECT *
FROM wp_before_after
WHERE patientID = 8175
AND patient_display = 1
AND period_taken = '1hour'
Hope this help

Get results from WPDB

I have this scenario that I can't figure out:
Inside table wp_comment I need to list all user_id (not duplicate) with comment_type=complete.
I tried this:
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'", ARRAY_A );
$corsisti = $results[user_id];
// I need to print only ids to put this array in
get_users( include=> '$corsisti' )
The database screenshot:
You can use the wpdb::get_col() method to retrieve an array with values from a single column:
$corsisti = $GLOBALS['wpdb']->get_col( "SELECT `user_id` FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'");
Then simply use the result in get_users (you do not need the quotes):
$users = get_users( include=> $corsisti );

Inserting data into MySQL while looping over a result set

How can I execute insert queries while retrieving data from database?
I mean that after running a select query where I am retrieving data using a while loop, I also want to insert some fields into another table.
I want to execute inserts forcefully in PHP code.
I tried:
$firstview=mysql_query("insert into kadam_firstview(jobtype,jobname,admin_id,date,datetime)values('".$trial."','".$jobname."','".$adminid."','".$time."','".$date."')");
$firstview.execute();
But it doesn't work.
i want to run upper query inside select query as i am getting data from select query at that same time i want to save those data inside another table but query giving error which is mentioned above
I think your question is more for php developer then for dba.
Anyway if I understand you correctly you would like to select a record set from a table and insert this values (or modified one) into another table?
<?php
$db = new mysqli("host", "username", "password", "databasename");
$result = $db->query("SELECT * FROM table_name");
while ($row = $result->fetch_object()) {
$trail = $row->trail;
$jobname = $row->jobname;
$adminid = 25;
$time = $row->time;
$date = $row->date;
$query = "insert into kadam_firstview(jobtype,jobname,admin_id,date,datetime) values('".$db->escape_string($trial)."','".$db->escape_string($jobname)."','".$db->escape_string($adminid)."','".$db->escape_string($time)."','".$db->escape_string($date)."')";
$db->query($query);
}
this will copy the rows from the table "table_name" into the table "kadam_firstview" and set the adminid to 25.
http://php.itronic.at/manual/en/class.mysqli.php

How do I change the case on every field in a mysql table in one call?

I have a table with 27 varchar fields. I want to make all fields lowercase, but i want to do it in one short mysql call.
This does a single field:
UPDATE table
SET field = LOWER(field)
How do I do the equivalent of this (which doesn't work):
UPDATE table
SET * = LOWER(*)
You can't do it with your creative attempt SET * = LOWER(*) etc.
You can however do it like this:
UPDATE table SET
column1 = LOWER(column1),
column2 = LOWER(column2),
-- etc, listing all text type columns
columnN = LOWER(columnN);
The reason there's no "shortcut" is probably because this pattern is so infrequently needed.
The consensus is that this cannot be done in a single mysql query.
Here is a super quick PHP script that does this for N fields (thanks for the idea #alex):
$sql = "SHOW COLUMNS
FROM table";
$results = mysqli_query($dbcon,$sql);
while($column = mysqli_fetch_assoc($results))
{
$column = $column["Field"];
$sql = "UPDATE table
SET $column = LOWER($column)";
$success = mysqli_query($dbcon,$sql);
}

generating MD5 idHash directly in MySQL statement

In my table I have an userID that is auto-incremented. In the same row I have an idHash. Is it possible to generate the idHash (simply an MD5 sum) from it directly with the same INSERT statement so that I don't have to SELECT the id, and then UPDATE the idHash again?
Problem is: I do not know the userID before it is being generated (auto-incremented) by MySQL.
Thanks
Frank
PS: I'm using PHP.
PPS: This question is all about a SINGLE INSERT. I know that I can use PHP or other languages to manually select the data and then update it.
I don't believe you can do it within a single INSERT statement.
What you probably could do is use an INSERT trigger, that both determines the new ID, hashes it, and then updates the record.
One solution I can recommend is using the last insert ID instead of re-querying the table. Here is a simplified example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users VALUES (....)";
$mysqli->query($query);
$newUserID = $mysqli->insert_id;
$query = "UPDATE users SET idHash = MD5(userID) WHERE userID = $newUserID";
$mysqli->query($query);
/* close connection */
$mysqli->close();
?>
AFAIK there's no "secure" way for doing this in the same query if you're using auto_increment.
However, if rows are never deleted in your table, you can use this little trick :
insert into mytable (col1, col2, col3, idhash)
values ('', '', '', md5(select max(id) from mytable))
I don't understand why you need to hash the id though, why not use the id directly ?
This seems to work for me:
CREATE TABLE tbl (id INT PRIMARY KEY AUTO_INCREMENT, idHash TEXT);
INSERT INTO tbl (idHash) VALUES (MD5(LAST_INSERT_ID() + 1));
SELECT *, MD5(id) FROM tbl;
Note this will only work on single-row inserts as LAST_INSERT_ID returns the insert ID of the first row inserted.
Performing MD5(column_name) on an auto_increment value does not work as the value has not been generated yet, so it is essentially calling MD5(0).
PHP snippet
<?
$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
?>
This will get you the next auto-increment and then you can use this in your insert.
Note: This is not perfect (Your method is imperfect as you will effectively have 2 primary keys)
From: http://blog.jamiedoris.com/geek/560/