Script for cron job not working. PHP/MySQL - php

I set up a cron job to run the following script every 30 min, Basically this script selects article info from stories table where field showing=0 And it than counts votes related to that article, the votes are located in votes table. itemname_field in votes table is equal to id field in stories table.
If you need more information on database structure and voting system, I describe it in depth here:
Set a cron job to update article information depending on its vote values
<?php
mysql_connect("localhost","username","password") or die (mysql_error("There was an error in connection"));
mysql_select_db("database") or die (mysql_error("There was an error in connection"));
$query = "select sum(vt.vote_value) as vote_value, vt.item_name from Votes vt join stories st on st.id = vt.item_name and st.showing = 0 group by vt.item_name";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
if($row['vote_value'] > 9) {
$showing = 1;
}
else if($row['vote_value'] < -9) {
$showing = 2;
}
else {
$showing = 0;
}
$query2 = "UPDATE `stories` SET `showing` = $showing WHERE `id` = '".$row['item_name']."'";
mysql_query($query2);
}
?>
Can anyone suggest the reason, why this script is not working? If everything is alright with script, could it be something in cron job that needs to be done?
EDIT: when I run script in browser it gives the following error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
Which is this line while($row = mysql_fetch_array($result))

The error message you quote means you have an error in your query. Run it though a mysql client to get more info, or echo mysql_error() in php.
In such cases mysql_query() returns boolean false, you can use this for error handling.

The issue was in this part:
$query = "... from Votes vt join ...";
it should not be capital "V".

Related

Getting value from MySQL, and putting them into other table (multiple values at once)

First and formost, yes i know PHP5.6 is deprecated version, but i want to stick with it and fully learn PHP for myself, before updating to MySQLi.
I'm trying to make a text based game running MySQL and PHP, and currently trying to create a system that:
1.Gets information from user table, username and total actions done (+)
2.At the certain timestamps save all usernames and actions into separete table (-)
3.Resets actions column to 0 for ALL players. (+/- planning to use a mysql trigger and/or cron-job)
My questions:
2) How would you suggest me to insert usernames into seperate table? (only idea i come up is to explode array somehow get variables and sumbit to mysql, question is how to do so? )
3) regarding this number 3, would you suggest something else then triggers or cron-jobs?
Code example bellow
<?php
include './config/connect-db.php';
$result= mysql_query("SELECT * FROM user WHERE actions > 100 ORDER BY
actions DESC LIMIT 5");
while($row = mysql_fetch_array($result)){
if ($row['u_dmisijos'] >= 100) {
echo '<li>'.$row["u_name"].' ('.$row["actions"].')<br>';
} // if actions
} //while loop
?>
EDIT:
MySQL includes a lot of columns, there are only 2 specific I'm focusing on, u_name (username) and actions (actions).
EDIT2:
What i am expecting on second table: ID (AI), username of player with the most action points, username of player with second action points etc. And Datastamp.
expected SQL
ID, nr1, nr2, nr3, nr4, nr5, Datastamp.
Cheers!
I am not sure this will work or not as I have not tested it. But, I hope you might get a general idea.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT * FROM user WHERE actions > 100 ORDER BY actions DESC LIMIT 5";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$q = "INSERT INTO `new_table` (`u_name`, `actions`) VALUES
($row['u_name'],$row['actions'] )";
mysql_query($q);
}
?>
Regarding resetting all actions to 0 you can create a functions like:
function resetActions(){
//update actions to 0
$q = "UPDATE table_name SET actions = 0";
mysql_query($q);
}
Now, whenever you need to reset it you can call this function. Or you can call this function in cron job as you required.

PHP - have a script call itself again to avoid timeout

I have a database with records to process. Number of records will vary. Too many records will cause my script to timeout but 15 records is a good safe number.
If my pseudo code is
//script begin
$sql = "SELECT id FROM table WHERE status = 0 LIMIT 0, 15";
runquery($sql);
foreach($rows as $row) {
//do things then run this sql:
$sql = "UPDATE table SET status = 1 WHERE id = {$theCurrentId};";
}
, can I achieve something like this at the end of the script:
$sql = "SELECT id FROM table WHERE status = 0";
runquery($sql);
if (rowcount() > 0) {
???? - something to call this script again as a new script
}
i.e. can I run this short script again if needed without it being counted in the timeout?

How to grab an int from my MySQL server via PHP?

I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.

MYSQL/PHP Unable to save result set

I am running a PHP script which basically tries to find matching names from MYSQL database and then assigns the same number to records with identical names.
My problem is that the number of records are around 1.5 million. The script always runs for about 14 hours every time and gives this error : mysql_query unable to save result set in xx on line xxx. and phpmyadmin gives this error #2008 out of memeory
Here is my php code
mysql_query("SET SQL_BIG_TABLES=1");
$res = mysql_query("SELECT company_name, country, id FROM proj")
or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_NUM)) {
$res1 = mysql_query("SELECT company_name, id FROM proj WHERE country='$row[1]'"+
"AND id<>'$row[2]'") or die ("here".mysql_error().mysql_errno());
while ($row1 = mysql_fetch_array($res1, MYSQL_NUM)) {
//My calculations here
}
}
Ok. Your query is incredibly inefficient. You say in a comment that there's 1.5 million rows.
Outside query creates a result set with all 1.5 million rows
Inside query creates a new result set with all 1.5 million rows, EXCEPT the row that has the same of the row you're looping on. So basically you're doing 1.5 million * (1.5 million - 1) rows =
2,249,998,500,000 = 2.25 trillion rows
In other words, not only incredibly inefficient - it's absolutely ludicrous. Given you seem to want to fetch only rows by country, why not do something like:
$sql1 = "SELECT DISTINCT country FROM proj";
$res1 = mysql_query($sql1) or die(mysql_error());
while($row1 = mysql_fetch_associ($res1)) {
$country = $row1['country'];
$escaped_country = mysql_real_escape_string($country);
$sql2 = "SELECT company_name, id FROM proj WHERE country='$country'";
$res2 = mysql_query($sql2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($res2)) {
... calculations ...
}
}
This'd fetch only 1.5 million + # of country records from the database, which is far far far less than the 2.3 trillion your version has.

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