Why isn't this script working? (odd/even) - php

I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?

The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";

Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()

Related

Comparing input data with data queried from database

So when I tried to get one random row in database and store it into variables, it seems like I cannot reuse those variables for my next sql query as I was tried in these lines.
First I get one random row in database and store it into variables for later use
$mysqli = new mysqli($hostname, $username, $password, $dbname, $port) or die(mysqli_error($mysqli));
$sqlcompare = "SELECT * FROM questions order by rand() limit 1";
$result = mysqli_query($mysqli, $sqlcompare);
$row = mysqli_fetch_row($result);
$pos = $row[0];
$word = $row[1];
$pos is the id of that row $word is the data of that row.
Then I get user input and checking the database if there is a row both have the same id with $pos and the input word is the same as that row
$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word = $input AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
if (isset($_POST['compare'])) {
if (mysqli_num_rows($sqlresult)>=1) {
echo "Found that input";
} else {
echo "Not found";
}
}
When I tried to retrieved word from database directly from user input, which only have one condition, the code work perfectly but when I add id condition in, it not working anymore. Any idea where I screw thing up?
Edit note: I just tried to echo $pos and $word and it work perfectly but somehow when I tried to put $pos varibale into sql to query, it does not working.
Use like instead of ( = ).
$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word LIKE '%".$input."%' AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
Mysql Like docs

incorrect result display from database

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

How to Compare Huge Array to Database (with PHP or SQL)

I have a big 2D array (576,000 X 4), and huge database (millions records and 10 columns, its size is in Gigabytes). The array, of course, is much smaller than the number of records in the database.
I need some effective way to compare the 2D array to the database, and delete the equal lines from the 2D array only.
Does anyone have an idea how could i apply it efficiently? The speed is very important to me.
I tried to apply it like that:
$query = mysqli_query($config, "SELECT * FROM sec ") or die(mysql_error());
while ($row = mysqli_fetch_array($query) ) {
if ( isset($arr[$row['CHROM']][$row['POS']]) ) {
// delete line from the 2D array
}
}
But, i don't know how efficient it is, because i tried it just on small database, and it makes me load all the records of the database to the PHP page, and it creates a memory problem.
Another way that i check is this:
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$query = mysqli_query($config, "SELECT * FROM sec WHERE CHROM='$chr' && POS='$pos' ") or die(mysql_error());
if (mysqli_num_rows($query) > 0) {
// delete line from the 2D array
}
}
}
But, its not a good solution, because it took too much time.
edit:
my sec table looks like that:
the call to a item from the 2D array looks like that $arr[some_CHAROM][some_POS]
if the some_CHAROM equal to some CHAROM in the database AND some_POS equal to the POS in the same line, we have a match.
i build the 2D array from a file that the user upload to the website. and im not load it to the mySql.
The algorithm:
convert the file uploaded by the user into a CSV file (if not already in this format); this is a simple task that can be done in several lines of PHP code; see function fputcsv();
create a buffer table: tbl1;
use LOAD DATA LOCAL INFILE to load the content of the (local) CSV file into the buffer table tbl1;
use:
DELETE tbl1
FROM tbl1
INNER JOIN tbl2 on tbl1.id = tbl2.id
to delete from table tbl1 the rows that have matches in table tbl2. I assumed the match field is named id on both tables; change it to match your design;
fetch the data from table tbl1, format it as you wish, send it to the browser;
cleanup: DROP TABLE tbl1;
Because the script processes a file uploaded by an user, in order to avoid any concurrency issue you need to generate for the buffer table an unique name for each user. You can use a prefix and append the userId to it to avoid two users using the same table on the same time.
Try following code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "drupal7";
mysql_connect($servername, $username, $password );
mysql_select_db($dbname);
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$database1=array();
while ($row = mysql_fetch_row($result)) {
$result1 = mysql_query("SELECT * FROM ".$row[0]);
if(mysql_num_rows($result1)){
$num_rows = mysql_num_rows($result1);
// echo "Table: {$row[0]} ==>".$num_rows."<br>";
$database1[$row[0]]=$num_rows;
}
// }
}
echo '<pre>';
print_r($database1);
mysql_free_result($result);
// mysql_close();
$dbname='drupal71';
mysql_select_db($dbname);
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$database2=array();
while ($row = mysql_fetch_row($result)) {
$result1 = mysql_query("SELECT * FROM ".$row[0]);
if(mysql_num_rows($result1)){
$num_rows = mysql_num_rows($result1);
// echo "Table: {$row[0]} ==>".$num_rows."<br>";
$database2[$row[0]]=$num_rows;
}
// }
}
print_r($database2);
$test = array_diff($database1, $database2);
print_r($test);die;
From your code snippet
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$query = mysqli_query($config, "SELECT * FROM sec WHERE CHROM='$chr' && POS='$pos' ") or die(mysql_error());
if (mysqli_num_rows($query) > 0) {
// delete line from the 2D array
}
}
}
I assume, that you want to delete based on $chr and $pos.
So, you could do the following: Assemble a single query to rule them all* :)
$ors = array();
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$ors[] = "CHROM='$chr' AND POS='$pos'";
}
}
$deleteConditions = "(" . implode(") OR (", $ors) . ")":
$query = mysqli_query($config, "DELETE FROM sec WHERE " . $deleteConditions);
Untested, but this should give you a single query, like
DELETE FROM
sec
WHERE
(CHROM='1' AND POS='2') OR
(CHROM='3' AND POS='4') OR
(CHROM='5' AND POS='6') OR
...
depending on what $chr and $pos are.
*As Ollie Jones noted in the comments: Take care of the overall query length. If required, create a second, third, ... query until you processed all items in appropriate batches.

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

autocomplete query to execute another mysql query if rows = 0 on first one using last keyword entered

I'm working on a type of spellcheck, autosuggest. I have two dictionaries, one with phrases, and one that should kick in for basic spelling suggestions. Right now I have this on the server side:
$q = strtolower($_GET["q"]);
$q= mysql_real_escape_string($q);
if (!$q) return;
$sql = ("SELECT headings FROM dictionary WHERE headings LIKE '$q%' LIMIT 3");
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$auto = $rs['headings'];
echo "$auto\n";
}
if (mysql_num_rows(mysql_query("SELECT headings FROM dictionary WHERE headings LIKE '$q%' LIMIT 3")) == 0){
$res = mysql_query("SELECT spelling FROM spellcheck WHERE spelling LIKE '$s%' LIMIT 3");
while($result = mysql_fetch_array($res)) {
$spell = $result['spelling'];
echo "$spell\n";
}
}
basically, $s should equal where the first query left off. So if the query was : hello wor. $s would be wor and it would suggest "world" from the mysql_query: $res. I would have to deal with multiple spaces between words too.
Use mysql_affected_rows() to get affected rows of last executed query...
refer http://php.net/manual/en/function.mysql-affected-rows.php

Categories