SQL - PHPmyadmin - Alter table order by 'id ascending' - Make permanent - sql

If I run this:
ALTER TABLE `equipos11a12` ORDER BY `ID`
It only happens one time. If I change the ids, it wont change in ascending order.
I have to run the alter table everytime in order for the ids to order.
Here is my php code:
$query = "SELECT * FROM equipos11a12";
$result = mysql_query($query); ?>
while($person = mysql_fetch_array($result)) {
echo " " . $person ["name"] . " ";

You must add the order by clause to your select query :
$query = "SELECT * FROM equipos11a12 ORDER BY `ID` ASC"; // ascending order
$query = "SELECT * FROM equipos11a12 ORDER BY `ID` DESC"; // descending order

Related

Retrieve a single columnSQLl from database

Which code do I need to retrieve a single value i from a column from table in SQL?
user_comment_count
This is column name in table
table is :
zmar_hreviews_list_total
This is code I use with error:
<?php
$insert1 ="/// ";
$string = "ars <pre>{$insert1}</pre>";
$query = 'SELECT user_comment_count FROM zmar_hreviews_list_total WHERE contentid = '.$item->getId();
$db->setQuery( $query );
$result = $db->loadResult();
if($result) {
$result = str_replace('*','',$result);
print_r($insert1); print_r($result);
}
?>
try:
select user_comment_count from zmar_hreviews_list_total

How to do select statement after THEN of SELECT CASE in SQL query?

Is it possible to write query which has select statement after THEN of SELECT CASE in SQL query?
Example of logic
SELECT Id, CASE WHEN level=2 THEN
(select something here)
else 0 end as Grade FROM CLASS
You could declare the second select as a variable.
For example:
DECLARE #var as int
SET #var = (SELECT COUNT(*) FROM table)
SELECT
Id,
CASE WHEN level=2 THEN #var else 0 end as Grade
FROM CLASS
Based on the PHP Documentation you could run something along these lines:
Start by creating your database connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
This if statement is checking for the table test if it does not exists then drop it OR create the table test with the field id which is an INT
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Then if the conditions are try you run your queries here; here they have three queries.
First - counts the total rows in the table (which will equal 0)
Second - add a value to the table
Third - count the total rows again, which this time will output "1"
// this is what you may be asking?
// they add to their sql query
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
Make sure that the queries have been built correctly
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Then run the code
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC)); // this will gather all records from the Database
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result()); // You can find the links for documentation for more_results() and next_result() below
?>
Documentation for more_results() and next_results()
Note the $sql as you can see they just create multiple queries that will run together if everything is true.
It will output this:
array(1) {
[0]=>
array(1) {
["_num"]=>
string(1) "0"
}
}
array(1) {
[0]=>
array(1) {
["_num"]=>
string(1) "1"
}
}
Please note, this is not my code, I got it from here

LastInserID from other table insert to table [duplicate]

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

SQL Query won't accept variables for ALL the parameters

I have a database table with an event_id column and a scheduled_at column.
The query is called in php and is as such:
$columnName = 'scheduled_at';
$start = '2013-02-26';
$end = '2013-02-27';
// query to be executed
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND $end );
The query does not work when executed, however the following does work
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND '2013-02-27' );
and
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND $start );
does not work, but the following does work
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN '2013-02-27' AND '2013-02-27' );
Inserting the value manually makes it work but loses the usefulness of the function. Any ideas why it would not work?
you need to quote your variables, so that the SQL string that is created containes quotes around the date values. eg
$sql = "( SELECT * FROM $table WHERE $columnName BETWEEN '$start' AND '$end' )";

sprintf and php

The following function gives all the related data except artist_id, when run I have checked all elements in the database and ok.
If I change the artist_id to an actual 'id' it shows in the result of the function as WHERE artist_id = 4 AND........
Confess I do not understand what is causing this.
Result of the function:
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE artist_id = AND member_id = 1 AND
image_album_id = 160
<?php
function get_data_nxtprv($fields, $where) {
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE artist_id = " . $artist_id. "
AND member_id = ".$_SESSION['member_id']." %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
//print_r($sql);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
?>
I am not entirely sure I understand your question. But I noticed that your function uses three input variables:
$artist_id, $fields, $where
But $artist_id is not getting passed as an argument.
You would need to modify the function call:
function get_data_nxtprv($artist_id, $fields, $where)
There is an error in your SQL
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE artist_id = AND member_id = 1 AND
image_album_id = 160
should it not be
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE member_id = 1 AND
image_album_id = 160
if artist_id is one of the fields you're looking for?