php change value to 0 from any number - php

guys
I don't know why but php convert my value into 0 each time.
So, i have video table.
Inside i have a row called like and dislike.
Lets say i have 10 dislike.
Every time i check previously value like that:
$sql = "SELECT * FROM video WHERE video_id = '$id'";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
$like=$row['vid_like'];
$dislike=$row['vid_dislike'];
and i echo dislike i got 10 in return
Just after that i do that for increase dislike:
$dislike1= $dislike +1;
echo "dis = {$dislike1}";
$sqla = "UPDATE video SET vid_dislike='$dislike1' AND vid_like='$like' WHERE video_id = '$id' ";
mysqli_query($conn, $sqla);
my echo result is 11. But when i check table after that query, my dislike value is set to 0...

Your update query is not well formatted.
It must look like this :
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
See documentation.
Here you wrote "AND" instead of a comma, which is by the way useless in this case since the second part is vid_like='$like' where $like value didn't change.

Related

php and mySQL database concurrency update

Lets say I wanted to increment a counter in a database every time someone visits a webpage.
The database called 'example' looks like this:
|Name.....| Value..........| id |
===================
|count......| 5................| 1 | <---- 1st row
and the code on the webpage looks like this:
$db = mysqli_connect("localhost", ....);
$q = "SELECT Value FROM example WHERE id = '1'";
$r=mysqli_query($db, $q);
$result = mysqli_fetch_array($r);
$increment = $result[0] + 1;
$q = "UPDATE example SET Value = '$increment' WHERE id = '1'";
mysqli_query($db,$q);
If two people access the webpage at the same time, person A will fetch the value of 5 and immediately after that, person B will fetch the same value. They will both increment it to six and both perform the update one after the other entering 6 as the counter value when it should really be 7 since two people visited the page. How can I prevent this?
you can do it in one statement:
"UPDATE example SET Value = Value + 1 WHERE id = '1'";
so also no other task can change it between your read and update.
Here your script
$db = mysqli_connect("localhost", ....);
$q = "UPDATE example SET Value = Value + 1 WHERE id = '1'";
mysqli_query($db,$q);

Cannot cast string to int (php)

I am trying to finish my question of the day script. I have a random number generator (external) which is inserted into a table daily. I take that number and pull the corresponding question from another table.
// Query 1
$query1 = "SELECT $field1 FROM $table1 WHERE id=1";
$result1 = mysqli_query($con1, $query1);
// Query 2
$query2 = "SELECT $field2 FROM $table2 WHERE QNum = $result1";
$result2 = mysqli_query($con2, $query2);
// Display question
while($row = mysqli_fetch_array($result2)) {
echo $row['question'];
}
$result1 is pulling a random number, lets say its 9. When $result1 is used to pull the question, it doesn't work but when I replace $result1 with number 9, it works. I experimented with syntax and eventually figured it could be a problem with a string vice an integer.
I tried to cast it as an integer but it keeps assigning the value of $result1 to 1. I am at a loss. I don't understand if the string is a 9, how converting it to an integer would change its value.
I feel like I've tried everything after days of experimenting out there but I am sure it is something very simple. Please help.
You're right, it's something very simple. You need to fetch the row to get the value:
$row = mysqli_fetch_assoc($result1);
$qnum = $row[$field1];
$query2 = "SELECT $field2 FROM $table2 WHERE QNum = $qnum";
You seem to understand this in general, since you call mysql_fetch_array to get the results of the second query. Why should the first query be any different?
However, you can do all this in one query:
$query2 = "SELECT t2.$field2
FROM $table1 t1
JOIN $table2 t2 ON t1.$field1 = t2.QNum
WHERE t1.id = 1";
Have you checked whats returned in $result1 ??
it should be an object which cannot be used inside the second mysql query. First you have to get the value from that query by fetching the query.
$result1 = mysqli_query($con1, $query1);
$row = mysqli_fetch_array($result1, MYSQLI_NUM);
$random_number = $row[0];
this $random_number then can be used in the second query. hope this will fix your error.

Getting last value of a field in mysql

I am trying to get the last value of a field during a new registration.
before insert data into the table, I want to create a user id number according to the last registered user's id number. to do that I use this:
//to reach the last value of userID field;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$value = $row['userID'];
echo "$value"; //not resulting here
}
$userID = $value+1;
so, the userID becomes 1.
The weird thing is, I could capable to use exact same code in another php file and works fine.
I would like to say that, rest of the code works fine. No problem with db connections or any other things you can tell me.
Note that: When I run the same query line in the mysql interface, I can get the value I want. I mean $sql line.
Your problem is in this code:
{
$svalue = $row['userID'];
----^
echo "$value"; //not resulting here
}
$userID = $value+1;
Change to $value.
But the right answer is to define userID to be auto-incrementing. That way, the database does the work for you. After inserting the row, you can do:
SELECT LAST_INSERT_ID()
To get the last value.
I solved the problem. Here;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
$user_info = $result->fetch_assoc();
$value = intval($user_info["userID"]);
$userID = $value+1;
Thanks everyone.
If you mark the userID field as autoincrement in you mysql table.
You won't need to set the userID and db increase the userID for you. You can get the assigned userID using the mysql_insert_id() function. Here is an example from php.net
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Here is another example for your case
mysql_query("INSERT INTO 'loto_users'('username',...) values('usernameValue',...)");
echo "New User id is ".mysql_insert_id();

Using MAX() in mySQL query is giving problematic results

I'm trying to make multiple queries in order to find the most recent entry in a database by username.
Here's my code:
<?php
require_once("../includes/db_connection.php");
$userID = $_POST["userID"];
$returnString = array();
// Query the max id value of a given key_id (find the most recent upload)
$query = "SELECT MAX(id) FROM photos WHERE key_id = {$userID}";
$result = mysqli_query($connection, $query);
//additional while loop could go here
//now get the url where from the max id value that we just queried
$query = "SELECT url FROM photos WHERE id = {$urlID}";
$result = mysqli_query($connection, $query);
$returnString['url'] = $urlID;
mysqli_free_result($result);
echo json_encode($returnString);
?>
I think the problem lies in the first query. When I return the result from that, I get:
{"maxID": "current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
When I create a while loop to capture the array (why I need to do this is beyond me because it will only ever return 1 value):
while($row = mysqli_fetch_assoc($result)) {$returnString[] = $row;}
Then I get this funky result:
[{"MAX(id)":"30"}]
30 is the correct value, but then I don't know how to use that result in my next mySQL query.
**********UPDATE*************
The query :
SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID});
Works perfectly when making the query from within mySQL, but doesn't work from my php script. It returns this weird string:
{"url":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}
Here's the updated script:
require_once("../includes/db_connection.php");
$userID = $_POST["userID"];
$returnString = array();
$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
mysqli_free_result($result);
$returnString['url'] = $result;
echo json_encode($returnString);
Unless I'm missing something in the schema that's not apparent from code and comments, you can save yourself a roundtrip by combining your SQL commands.
$query = "SELECT id AS urlID, url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
Then interface with your results like you normally would.
Updated answer:
$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result):
$url = $row['url'];
echo json_encode($url);
mysqli_free_result($result);
I think the real problem is in the loop and use of an array for the results.
You should change to a single query like:
SELECT url, MAX(id) as id FROM photos WHERE key_id = {$userID}
MAX(id) as id returns the aggregate column name as id
You don't need to loop with a while if you are only expecting one row. Just change the while to if to test if any row is returned, and assign the values to single variables:
$id = {$row['id']};
$url = {$row['url']};
The "funky" result is from trying to print the array which is not needed and has stored the column name and value.

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