mysql queries which is the best - php

i want to know which way is better (faster) from those sql methods;
1st method:
public static function getlistusers($limit=88888888888888 ) {
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
$list = array();
while ( $row = mysql_fetch_assoc($st) ) {
$picss = new users( $row );
$list[] = $picss;
}
return ( array ( "users" => $list) );
#mysql_free_result($st);
for print output i use
foreach() the array $users ;
2nd method
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
while ( $row = mysql_fetch_assoc($st) ) {
extract($row);
return "Id: $id and The Name is : $name";
}
#mysql_free_result($st);
}
===========
i want to know which is faster and safty for sql load.
Regards
Al3in

$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
while ( $row = mysql_fetch_assoc($st) ) {
extract($row);
return "Id: $id and The Name is : $name";
}
#mysql_free_result($st);
I doubt this approach will even work. Because, even though you limit it to 1 or a million, the loop will only run once because of return "Id: $id and The Name is : $name"; . So if you're comparing this and the other method, the other method would obviously work better.
Unless you're assigning to an array instead of returning. In which case the second method has an unnecessary function call extract which puts two variables into the heap.

Both are essentially the same. They execute the same query and retreive the results in the same way. The advantage of the first method is that it returns a list of data arrays that each represent a records in the database. All individual can be used any way you want. The second approach returns only a single string. The entire while loop is useless there.
So the second may be faster, because it only retrieves a single row, but from here that looks more like an error than like an actual implementation decision.

Related

Foreach loop only outputting one value

I have a foreach loop that should add a row to the table "notifications"
$infoquery = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query($dbc, $infoquery);
$rows = mysqli_fetch_array($identifier);
foreach(array_unique($rows) as $row){
$core->addNotification($row['user_id'], $link, $description);
}
however it is only adding one value, when it should add two notifications, one for user 1 and one for user 3
You are fetching only one single row, it should be like this:
$infoquery = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query($dbc, $infoquery);
while($row = mysqli_fetch_array($identifier)){
$core->addNotification($row['user_id'], $link, $description);
}
Aside from tkausl's correct answer, your other problem is unique visitors: array_unique compares the string values of an the items in the array.
Let's look at this:
var_dump(strval(array("bob")), strval(array("ed")));
Which outputs:
string(5) "Array"
string(5) "Array"
(and a whole load of errors).
So, as their string representation is the same, if you expect an multidimensional array array(array("user"=>"bob"),array("user"=>"ed")), you will remain with only one entry in there. Now, there's a whole lot of ways to work around that in PHP, but your database is better at it, use:
SELECT DISTINCT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
(But do look into prepared statements instead of adding raw parameters / query building).
Alternatively if you have a small result set, you could use that result to get all the data at once and avoid using iteration to fetch the data by using $result->fetch_all according to the manual (see http://php.net/manual/en/mysqli-result.fetch-all.php), as follows:
<?php
$query = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query( $dbc, $query );
$result = $mysqli->query( $query );
$rows = $result->fetch_all( MYSQLI_ASSOC );
foreach ( $rows as $row ) {
$core->addNotification( $row['user_id'], $link, $description );
}

Create single PHP Function for similar queries but with different WHERE clauses

I'm not sure if this is doable or not, and I'm not entirely sure how to search for this. I have several dynamic web pages that all link to the same MySQL database table, but pull different results. So for example, a dynamic web page with ID = 5 will run a query like:
SELECT * FROM myTable WHERE category1 = 1
The web page where ID = 7 will run:
SELECT * FROM myTable WHERE category2 = 1
And so on. The queries are all grabbing the data from the same table, but the WHERE clause is different for each query - its not looking at the same column. The page with ID 7 should ONLY be returning results where category2 = 1, and ignoring the results that would be returned for the page with id = 5. My website has about 20 different pages/queries like this which is why I'm looking to see if it can be done in a function instead.
Is there a way I can put that into a function, and if so, how would I set up the parameters correctly? Or is this an instance where I will have to just write out all the queries separately on each page?
function find_results(what to put here?) {
global $connection;
$query = "SELECT * FROM myTable WHERE (how to code this part?)";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
You would add the necessary parameters to your functions argument list, then provide the values at runtime.
function find_results($column, $value)
{
global $connection;
$query = "SELECT * FROM myTable WHERE {$column} = $value";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
//Usage:
$result = find_results("category2", 1)
If the value you are returning records by ever ends up being a string make sure your wrap $value in single quotes.
if its a constant relation between pageId and categoryId, you can just create an array to hold it indexed by pageId like:
$pageIdToCategoryMapping = [
1 => 'cateogory1',
2 => 'category5',
...
]
and then just use it to pass data to your function like
find_results($pageIdToCategoryMapping[$pageId])
function find_results($category) {
(...)
$query = "SELECT * FROM myTable WHERE ({$category} = 1)";
(...)
}
I have been using class and object methods for mysql operations. source code available in github
I would recommend you to pass array as an argument and can return query or result as array in format you required. And this function will work any number or condition
<?php
$arg['db']="database";
$arg['tabe']="table";
$arg['search']['id1']="id1";
$arg['search']['id2']="id2";
//
function searchAndReturnResultAsArray($arg)
{
$return = NULL;
$query="SELECT * FROM ".$arg['table'];
$flag=false;
foreach($arg['search'] as $key=>$value)
{
if($flag)
$query.=" AND ";
else
$flag=true;
$query.= $key." = '".$value."' ";
}
$row = mysqli_num_rows($query);
$field = mysqli_fetch_object($query);
if($row >= 1)
{
while($data = mysqli_fetch_array())
{
$return[] = $data;
}
}
return $return;
}
?>
Or alternatively you can just return query once it is ready.

Created a new variable by pulling a value from a MySQL table

I am using a page where a variable $submissionid is being posted to it. I would like to use this variable and pull the field subcheck from a MySQL table called submission. I would like the value of the field subcheck to simply be a new variable $subcheck. I'm not sure how to do this. I have a query below, but how to I convert the result of the query below into a variable called $subcheck? (For any given submissionid, there will only be one $subcheck.)
Thanks in advance,
John
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '$submissionid' ");
mysql_query($querysub) or die(mysql_error());
You can try:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = ".
mysql_real_escape_string($submissionid));
$result = mysql_query($querysub);
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$subcheck = mysql_result($result, 0);
This is more of a 'php' question, than it is for mysql.
Look up the 'extract' keyword for PHP Link. Effectively 'extract' takes the contents of an associative array and creates php variables (symbol table entries) using the names of keys. Each php variable will then contain the associated value.
You should be able to just:
$result = mysql_query("SELECT * FROM table");
$row = mysql_fetch_array( $result, MYSQL_ASSOC );
extract( $row ); // Create php variables, named after each column in the table.
$row["field"] == $field; // Will be a true statement after 'extract()'
Enjoy, you now have the ability to have your code dynamic adjust to a DB schema that could be changed.
-- J Jorgenson --
This should work:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '" . $submissionid ."' ");
$result = mysql_query($querysub) or die(mysql_error());
$row = mysql_fetch_assoc( $result );
if ($row ) {
$subcheck = $row['subcheck'];
} else {
echo "Subcheck not found";
}
Be careful with the escape characters around $submissionid in your query string. In your sample, they are probably letting the name of the variable go into the string you send to the mysql server.

most efficient way to print a list of names based off a csv using php and mysql

I have an array of player's IDs. There will generally be about 5 players, not likely to be more then a dozen:
$cplayers= array(1,2,5);
I want to display the players names as a list.
$query = "SELECT username,id FROM users ORDER BY id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$playercounter =0;
while ( $row = mysql_fetch_array($result) ) {
if ($row['id'] == $cplayers[$playercounter]) {
echo "<li>".$row['username']."</li>";
$playercounter++;
}
}
So I'm pretty sure this isn't the most efficient way I could do this. Would it be better to do individual queries?
Also is there a good way to exit the while loop once $cplayers is done?
just change your query to this:
$query = "SELECT username,id FROM users WHERE id IN (".implode(",",$cplayers).")ORDER BY id";
this will return the correct players you're looking for.
Based on how I'm interpreting this, I'd use the MySQL IN clause, e.g.
$id_list= array(1,2,5);
$sql= 'SELECT username FROM users WHERE id IN('. join(",",$id_list) .') ORDER BY id';
$result= mysql_query($sql) OR die(mysql_error());
while($row= mysql_fetch_assoc($result)) {
echo "<li>{$row['username']}</li>";
}
This targets only those id values in the list, is that what you want?
Well apparently the answer is rather to normalize my database, have a separate (third) table for the join of the two rather than using an array w/in the second table.

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories