How to make a MySQL column value equal a variable in PHP - php

I have in my database a column called counter, i'm trying to save one of the rows of that column into a variable in PHP and make it equal the column rating. I do not want to make it from sql directly, I need to make it through php.
The problem is that when I run the query, the value for rating does not change at all. Please give me a solution
$cntrvalue = "SELECT counter FROM schools WHERE name = 'School1'";
$cntrResult = $this->conn->query($cntrvalue);
$mys1 = "UPDATE schools SET rating = $cntrResult WHERE name = 'School1'";
$this->conn->query($mys1);
Thanks
EDIT:
Sorry the code above gives an error, this is the code that changes nothing
$cntrvalue = "SELECT counter FROM schools WHERE name = 'School1'";
$this->conn->query($cntrvalue);
$mys1 = "UPDATE schools SET rating = $cntrvalue WHERE name = 'School1'";
$this->conn->query($mys1);
EDIT 2:
What i'm trying to do now is that i'm trying to get the value of a SUM query:
$mys4 = "SELECT SUM(`s1`+`s2`*2 +`s3`*3 + `s4`*4 + `s5`*5) FROM schools WHERE name = 'School1'";
$mys4Result = $this->conn->query($mys4);
$mys4Value = $mys4Result->fetch_assoc()[''];
The thing is that there is no column in the db to fetch from for this operation. What am I supposed to do? Thanks

Want you want to achieve, can be done within one mysql query, but if you just want how to fix that code:
You need to use the $cntrResult outside the string. Try string concatenation.
First you need to make sure, you have the correct value, as $cntrResult is not an string object, its an resultset:
$value = $result->fetch_assoc()['counter']
And the query:
"UPDATE schools SET rating = '" . $value . "' WHERE name = 'School1'";

Related

add one (+1) to a field in mysql database using php

I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.

WHERE clause doesn't seem to work in PHP

The query SELECT * FROM TABLE WHERE id LIKE '%1% is not working properly, it's not select the id 1.
mysql_connect('localhost', 'root' , '');
mysql_select_db('database');
$sql = ("select * from search WHERE id LIKE '%3%'");
mysql_query($sql);
$my_variable = mysql_query($sql);
$display_data = mysql_fetch_row($my_variable);
while ($list = mysql_fetch_assoc($my_variable)) {
$id = $list['id'];
$title = $list['title'];
$keywords = $list['keywords'];
$img = $list['img'];
$link = $list['link'];
}
If you are looking to SELECT id 1 then use = not LIKE. The way LIKE is being used it will match every id that has a 1 in it and you are not guaranteed to get the first one in order, so instead use:
SELECT * FROM search WHERE id = 1
According to the PHP documentation of mysql_fetch_row it
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
Which means that the first result won't show up in the next (mysql_fetch_assoc) procedure. You could try removing the $display_data = mysql_fetch_row($my_variable); line and only use the while($list = mysql_fetch_assoc($my_variable)) { ... } procedure. See if that solves your problem.
$sql = ("select * from search WHERE id ='3'");
The id is an integer use = instead of like . Equal is more accurate.
And first echo your query in your program->
echo $sql;die;
copy that query and run it on your phpmyadmin
and then check is your column id is int type if it is then like will not give you the result. You have to use the where clause here .But if you have the column id is of type varchar then definitely give you the result .
Try to use search tab under your database->table in your phpmyadmin and put the condition there.
You will definitely get your answer there.

Select SUM() as a variable in a for Loop

I'm trying to generate XML from database and need to gather a specific amount of data based on the average from a column. This can vary from anywhere between 5 to 30 queries for the $numItems variable.
I need to execute a for loop and assign the column name in the SUM($variable) but I'm not getting any data (but no errors either).
Here is my code:
for ($t = 1; $t <= $numItems; $t++){
$query = mysql_fetch_assoc(mysql_query("SELECT SUM(column'".$t."') AS value_sum FROM scoring WHERE ID='" . $userID . "' AND name ='" . $name . "'"));
$q = $query['value_sum'] / $totalUsers;
echo "<output".$t.">" . $q . "</output".$t.">\n";
}
The problem is assigning the SUM(column1) variable name for the column I'm getting data from, when I write the queries individually it works, but assigning the variable within the statement is causing a problem. Can any one give me any pointers?
Thanks in advance.
It looks like you might have extra single quotes in your query. I think it should be:
"SELECT SUM(column".$t.")..."
You should also consider doing a single select. Doing multiple database calls inside a for loop will be a huge performance problem. You could write a single select like this:
"SELECT SUM(column1), SUM(column2), SUM(column3),..."
Looks like bad escaping/concatenation around the column name...
"SELECT SUM(column{$t}) AS value_sum FROM scoring WHERE ID='{$userID}' AND name ='{$name}'"
Is that what you want?
Also use PDO!

MySQL table row will not UPDATE

I am trying to update a column in a row in a MySQL table. The column is the 'votes' column and when someone submits an HTML form there is a hidden input with a value of "1" that gets submit and posted. This is the code I am using to try to update the vote count:
if(isset($_POST['image_id']) && isset($_POST['vote'])){
$image_id = $mysqli->real_escape_string($_POST['image_id']);
$vote = $mysqli->real_escape_string($_POST['vote']);
$sql_users_vote = "SELECT * FROM users WHERE id='$image_id'";
$result_users_vote = $mysqli->query($sql_users_vote);
$row_vote = mysqli_fetch_array($result_users_vote);
$votes_count = $row_vote['votes'];
$new_votes = $votes_count + $vote;
$sql_vote = "UPDATE users WHERE id='$image_id' SET votes=$new_votes";
$result_vote = $mysqli->query($sql_vote);
}
I have echo'ed out the variable up until $sql_vote and $image_id, $vote, $votes_count and $new_votes all echo out the correct values. I'm guessing that there is a problem in the UPDATE syntax. I've checked it over and over but can't seem to find anything. I know that I don't have quotes around $new_votes in the UPDATE because I believe that is correct syntax. I've tried it with quotes and it doesn't work that way either.
Can someone help me identify the problem? Thanks!
Doesn't the SET come before the WHERE?
$sql_vote = "UPDATE users SET votes = $new_votes WHERE id = '$image_id'"
Or does it not matter?
$sql_vote = "UPDATE users SET votes=$new_votes WHERE id='$image_id'";

Adding the value of a variable to a database field

I have a MySQL database table called submission with a field called points with a type of bigint(100).
On a PHP file, I have a variable called $commentpoints with a numerical value.
In the PHP file, how could I add $commentpoints to points?
It's a matter of adding it in your SQL update query:
$sql = 'UPDATE submissions
SET points = points + ' . (int) $commentpoints . '
WHERE id = ' . (int) $id;
That will add the value of $commentpoints to the points in the database; just make sure to use the where clause so you don't add it to every record in the submissions table.
UPDATE table SET points = '[your value]'
mysql_query("UPDATE submission SET points = '$commentpoints'");
$sql = "UPDATE submission
SET points = points + ?
WHERE commentid=?";
$q = $conn->prepare($sql);
$q->execute(array($commentpoints,$commentid));

Categories