Simple SQL request is failing - mysql

I try to count the number of roles in my Drupal database and with the result execute another statement. But for some reason, it's failing. What do I do wrong?
$numberofroles = db_query('SELECT COUNT(rid) FROM {role}');
$roles = 1;
while ($roles < $numberofroles) {
db_query('INSERT INTO {taxonomy_access_default} (vid, rid, grant_view, grant_update, grant_delete, grant_create, grant_list) VALUES(0, '.$roles.', 1, 0, 0, 0, 1)');
$roles++;
}

You forget a? ->fetchField() ?
Drupal6:
$val = db_result(db_query({...}))
Drupal7:
$val = db_query({...})->fetchField();

What does db_query return? Your SQL query will return a single column and a single row, but does db_query return an integer or the result set as an array?
print $numberofroles (tip: $numberOfRoles is a lot easier to read) and see what the value is. If it prints as array() then you need to process the array and extract the value you want, likely $numberofroles[0][0]

Related

how to display count() sql function using php

how to display count() sql function using php
$results = "SELECT count(votesnumber) FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['votesnumber'];
} else {
echo "error";
}
i want to display the results of sql count() function using php. am counting specific columns WHERE ID = "some value" in phpmyadmin its working but with php its giving me headache . any ideas on how to solve this?
Try this:
$results = "SELECT count(votesnumber) AS VoteNum FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['VoteNum'];
} else {
echo "error";
}
First, if you want to refer to the column name by a reference, then you need to give it a better name using an alias:
SELECT COUNT(votesnumber) as votesnumber
ROM `votes`
WHERE `candidate_id` = '$candidate_id';
Second, you should not be munging query strings with parameter values. Instead of '$candidate_id', learn to use parameters. This prevents unexpected syntax errors and SQL injection accounts.
Third, if votesnumber is actually a number of votes, then you probably want SUM() rather than COUNT().
You need to add "AS" instruction to your SQL if you want to get this data as a specific index from array (like $rowresults['votes']):
$results = "SELECT count(votesnumber) AS votes FROM `votes` WHERE `candidate_id` = '$candidate_id'";
Remember that you can always print_r() (for arrays) or var_dump() your variable to check if it contains data you want to have.

Using multiple values in MySQL query parameters (... IN ('value', 'value')...) [duplicate]

How would you write a prepared MySQL statement in PHP that takes a differing number of arguments each time? An example such query is:
SELECT `age`, `name` FROM `people` WHERE id IN (12, 45, 65, 33)
The IN clause will have a different number of ids each time it is run.
I have two possible solutions in my mind but want to see if there is a better way.
Possible Solution 1 Make the statement accept 100 variables and fill the rest with dummy values guaranteed not to be in the table; make multiple calls for more than 100 values.
Possible Solution 2 Don't use a prepared statement; build and run the query checking stringently for possible injection attacks.
I can think of a couple solutions.
One solution might be to create a temporary table. Do an insert into the table for each parameter that you would have in the in clause. Then do a simple join against your temporary table.
Another method might be to do something like this.
$dbh=new PDO($dbConnect, $dbUser, $dbPass);
$parms=array(12, 45, 65, 33);
$parmcount=count($parms); // = 4
$inclause=implode(',',array_fill(0,$parmcount,'?')); // = ?,?,?,?
$sql='SELECT age, name FROM people WHERE id IN (%s)';
$preparesql=sprintf($sql,$inclause); // = example statement used in the question
$st=$dbh->prepare($preparesql);
$st->execute($parms);
I suspect, but have no proof, that the first solution might be better for larger lists, and the later would work for smaller lists.
To make #orrd happy here is a terse version.
$dbh=new PDO($dbConnect, $dbUser, $dbPass);
$parms=array(12, 45, 65, 33);
$st=$dbh->prepare(sprintf('SELECT age, name FROM people WHERE id IN (%s)',
implode(',',array_fill(0,count($parms),'?'))));
$st->execute($parms);
There is also the FIND_IN_SET function whose second parameter is a string of comma separated values:
SELECT age, name FROM people WHERE FIND_IN_SET(id, '12,45,65,33')
decent sql wrappers support binding to array values.
i.e.
$sql = "... WHERE id IN (?)";
$values = array(1, 2, 3, 4);
$result = $dbw -> prepare ($sql, $values) -> execute ();
Please take #2 off the table. Prepared statements are the only way you should consider protecting yourself against SQL injection.
What you can do, however, is generate a dynamic set of binding variables. i.e. don't make 100 if you need 7 (or 103).
I got my answer from: http://bugs.php.net/bug.php?id=43568.
This is my working mysqli solution to my problem. Now I can dynamically use as many parameters as I want. They will be the same number as I have in an array or as in this case I am passing the ids from the last query ( which found all the ids where email = 'johndoe#gmail.com') to the dynamic query to get all the info about each of these id no matter how many I end up needing.
<?php $NumofIds = 2; //this is the number of ids I got from the last query
$parameters=implode(',',array_fill(0,$NumofIds,'?'));
// = ?,? the same number of ?'s as ids we are looking for<br />
$paramtype=implode('',array_fill(0,$NumofIds,'i')); // = ii<br/>
//make the array to build the bind_param function<br/>
$idAr[] = $paramtype; //'ii' or how ever many ?'s we have<br/>
while($statement->fetch()){ //this is my last query i am getting the id out of<br/>
$idAr[] = $id;
}
//now this array looks like this array:<br/>
//$idAr = array('ii', 128, 237);
$query = "SELECT id,studentid,book_title,date FROM contracts WHERE studentid IN ($parameters)";
$statement = $db->prepare($query);
//build the bind_param function
call_user_func_array (array($statement, "bind_param"), $idAr);
//here is what we used to do before making it dynamic
//statement->bind_param($paramtype,$v1,$v2);
$statement->execute();
?>
If you're only using integer values in your IN clause, there's nothing that argues against constructing your query dynamically without the use of SQL parameters.
function convertToInt(&$value, $key)
{
$value = intval($value);
}
$ids = array('12', '45', '65', '33');
array_walk($ids, 'convertToInt');
$sql = 'SELECT age, name FROM people WHERE id IN (' . implode(', ', $ids) . ')';
// $sql will contain SELECT age, name FROM people WHERE id IN (12, 45, 65, 33)
But without doubt the solution here is the more general approach to this problem.
I had a similiar problem today and I found this topic. Looking at the answers and searching around the google I found a pretty solution.
Although, my problem is a little bit more complicated. Because I have fixed binding values and dynamic too.
This is the mysqli solution.
$params = array()
$all_ids = $this->get_all_ids();
for($i = 0; $i <= sizeof($all_ids) - 1; $i++){
array_push($params, $all_ids[$i]['id']);
}
$clause = implode(',', array_fill(0, count($params), '?')); // output ?, ?, ?
$total_i = implode('', array_fill(0, count($params), 'i')); // output iiii
$types = "ss" . $total_i; // will reproduce : ssiiii ..etc
// %% it's necessary because of sprintf function
$query = $db->prepare(sprintf("SELECT *
FROM clients
WHERE name LIKE CONCAT('%%', ?, '%%')
AND IFNULL(description, '') LIKE CONCAT('%%', ?, '%%')
AND id IN (%s)", $clause));
$thearray = array($name, $description);
$merge = array_merge($thearray, $params); // output: "John", "Cool guy!", 1, 2, 3, 4
// We need to pass variables instead of values by reference
// So we need a function to that
call_user_func_array('mysqli_stmt_bind_param', array_merge (array($query, $types), $this->makeValuesReferenced($merge)));
And the function makeValuesreferenced:
public function makeValuesReferenced($arr){
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
Links for getting this 'know-how': https://bugs.php.net/bug.php?id=49946, PHP append one array to another (not array_push or +), [PHP]: Error -> Too few arguments in sprintf();, http://no2.php.net/manual/en/mysqli-stmt.bind-param.php#89171, Pass by reference problem with PHP 5.3.1

Keep receiving error on SELECT SUM Query

Okay, so I found the mysqli format:
$resultDN7 = $db->query("SELECT SUM(`donation_resources`) as `totalDN7` FROM ztn_com_donations WHERE donation_playerid='$player_id' AND donation_corpsid='$player_corpsid' ");
$rowDN7 = $resultDN7->fetch_assoc();
echo $rowDN7['totalDN7'];
$pladon = ( $rowDN7['totalDN7'] );
Okay if you notice that last line, I must get the result changed into a variable. I could not find documentation on that, just an example as below:
if ($rowDN7)
{ $pladon = $row[0]; }
Is this correct?
mysql_result() expects parameter 2 to be int and you are giving it string
The documentation says
The row number from the result that's being retrieved. Row numbers start at 0.
Since in your case DISTINCT SUM(donation_resources) it will only return 1 row
It should be like
echo mysql_result($resultDN7, 0);
Where $resultDN7 is the resource and 0 is the row

Getting the max row character length in a query using Perl DBI Mysql

Using: Perl v5.10.1, MySQL 5.5.15, DBI.
I need to deliver end users output from a database via email. They do not want this as an attachment, but in the body.
I'd like to deliver the data in an ascii table and am having issues determining if DBI has built in functions to do this (output similar to querying MySQL from the command line).
Or If I can determine the longest row character length I can use that to build the table. I have a way to get the max item length in an array, but I can't wrap my head around doing it with the query results.
my $spacer_length = (reverse sort { $a <=> $b } map { length($_) } #array)[0];
Assuming a generic DBI loop, you could do something like this:
use List::Util qw(max);
...
my #output;
my $max;
while (my #foo = $dbi->fetchrow_array) {
$max = max($max // (), map length, #foo);
push #output, \#foo; # save data for email attachment
}
Using the "defined-or" operator // to avoid an undef warning and possible contamination in case of negative values.
I'm not sure exactly what you're asking for, but if you're looking for the "max row character length" for a given column of a query result, you can do that with SQL:
SELECT MAX(CHAR_LENGTH(col1)) FROM t1
or if you want all of the rows sorted by the length of the values of col1:
SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC
you can execute these queries using DBI like this:
# $mysql is your DBI connection info
my $query = $mysql->prepare("SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC");
$query->execute();
and then iterate through the result rows:
while ( my #result = $query->fetchrow_array ) {
my ($col1,$col2) = #result;
# do stuff with the values
}
and you can print the values as you wish, including like the output from the command line mysql client.

number of parameters requested in a select statement

This is probably a somewhat simple question but I am trying to make sure that a query statement (specifically a select statement) contains a specific number of parameters only:
$result = mysql_query("select type,some_other_column from my_table");
$row = mysql_fetch_array($result);
$number = count($row);
print $number;
This returns twice the number I think it should return (4) - as I believe it must also be returning the key and the value as separate parameters.
The select statement above is just an example and it could be any number of statements. They could be a lot more complicated and the tests I have run do not seem to have any problems. I want to make sure that there are only ever two parameters (it can be any two) and they could be from different tables too.
I just want to make sure that it that what I am doing above is both the fastest way to check that the number of parameters is correct and that it won't get upset if there is a much more complicated statement given to it.
I am sure there is a really easy answer to this. Thanks in advance for any help.
Try mysql_fetch_assoc or mysql_fetch_row. Both functions available on php.net
mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both. You end up having
$row["type"] = "somevalue"; // AND
$row[0] = "somevalue";
hence double the number
Whatever you SELECT would be in the $row variable, so in your code:
$result = mysql_query("select type,some_other_column from my_table");
$row = mysql_fetch_array($result);
/*
$row = array(
'type' => 'type_value',
'0' => 'type_value',
'some_other_column' => 'col_value',
'1' => 'col_value'
)
*/
$number = count($row);
print $number; // prints 4
I am not sure i understood your question right.
Do you just want to limit your number of returned values to one row?
If this is your point, you can add LIMIT 1 to your SQL-Query. This would, as it says, limit the number of results to one row.