My Insert query is :
function CreateResult($init_quizz_id,$result_title,$result_image,$result_description) {
$sql = "INSERT INTO result_quizz(init_quizz_id,result_title
,result_image,result_description)
VALUES('$init_quizz_id','$result_title','$result_image','$result_description')";
if ( $GLOBALS['conn']->query($sql) === TRUE) {
echo "Result Added";
$sql2 = "UPDATE 'init_quizz' SET 'results_count' = 'results_count' +1 WHERE 'quizz_id' = '$init_quizz_id'";
$GLOBALS['conn']->query($sql2);
if (!$GLOBALS['conn']->query($sql2)) {
echo ' NO UPDATE';
}
}
}
Lets say i have init_quizz table with the questions, and another table quizz_results. I want to increase the results_count on every quizz when result is added. My result table is hoilding also an init_quizz_id which is the actual ID of the quizz.
Im beginner so im looking for any solution to that.
Thanks
edit: fixed the error on the second query( sql2 ) and getting "not updated" msg. Seems like my second query is completely wrong. Any ideas?
#barmar was right, i found a better solution for my counter instead of UPDATE, i just returning the affected rows which have quizz_id from my results table.
function GetResultsCountByID($quizz_id) {
global $conn;
$sql = "SELECT * FROM result_quizz WHERE init_quizz_id = '$quizz_id'";
$result = $conn->query($sql);
return mysqli_affected_rows($conn);
}
Related
I am looping through the rows of the database with fetch_assoc() and I am selecting two columns of it. I check the values of these two columns of each row. If they are between 2 values then I updated a third row as 1(TRUE) if a statement is true. I am creating two connections because there are two statements, the one that selects the information and the other that updates the column that I want to be updated. When I try to print the information in the screen it seems that the SELECT statement works but when I try to UPDATE the column that I want the UPDATE statement does not update the database. Here is my code:
$conn= mysqli_connect("localhost","root","root");
$variablech = 1 ;
$query = "SELECT Client, Info FROM DataTable";
if ($result = mysqli_query($conn, $query)) {
while($row=mysqli_fetch_row($result)) {
if((($row['Client']>=54.055) && ($row['Client']<=54.117) ) && (( $row['Info']>=-4.827) && ( $row['Info']<=-4.317)))
{
$variablech = 0;
$sql= " UPDATE DataTable SET InfoData='$variablech' WHERE Client='".$row['Client']."' AND Info='".$row['Info']."'";
$conn->query($sql);
echo "yes";
}
else
{
$variablech = 1;
$sql= " UPDATE DataTable SET InfoData='$variablech' WHERE Client='".$row['Client']."' AND Info'".$row['Info']."'";
$conn->query($sql);
echo "no";
}
}
}
This should do the trick:
...
$sql= "UPDATE DataTable SET InfoData='".$variablech."' WHERE Client='".$row['Client']."' AND Info='".$row['Info']."'";
mysqli_query($conn, $sql)
...
Suggestion:
Not sure, if you have an auto_increment field in your table. If you do, then select it in select query and then use the same to update the data in update query. That will speed up the database stuff and so is your project.
What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.
Something is wrong with my php,
I'm doing an account validation where if the data exist it will display "There is data" and else "No data"...
When I enter the first 'row' reference_id and submit, it shows "There is data" which is correct but when I entered the second to the last 'row' reference_id it shows "No data" even though it exist in my Database!
Database:
reference_id (varchar 250)
status (varchar250)
PHP
if (isset($_POST['submit_valid'])) {
if (!empty($_POST['reference_id']))
{
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
if ($result['reference_id'] == $_POST['reference_id'])
{
echo"<script type='text/javascript'> alert('There is data'); window.location.href='next_page.php'; </script>";
}
if ($result['reference_id'] !== $_POST['reference_id']) {
echo"<script type='text/javascript'> alert('No data.'); window.location.href='this_page.php'; </script>";
}
}
}
I am not sure if it's the mysqli_fetch_array fault or the if-else condition is wrong?
if you guys know the problem please help me?
Your query execution currently only looks at the first row. A fetch needs to be looped to iterate over all rows. e.g.
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
should be
$query = mysqli_query($con, "SELECT * FROM client_record");
while($result = mysqli_fetch_array($query)) {
but this is inefficient. When looking for a specific record use a where clause. Parameterized queries also will prevent SQL injections, and quoting issues. The i in the bind_param is for an integer, if your id is a string use s.
$prepared = mysqli_prepare($con, "SELECT * FROM client_record where reference_id = ?");
mysqli_stmt_bind_param($prepared, 'i', $_POST['reference_id']);
mysqli_stmt_execute($prepared);
mysqli_stmt_store_result($prepared);
while (mysqli_stmt_fetch($prepared)) {
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
This will give you the first row from the table.
Add a WHERE reference_id = :refid clause?!
Then bind the refid parameter, so as to avoid SQL injection.
Lapiz, the problem is actually with the comparison operator:
($result['reference_id'] == $_POST['reference_id'])
This will check the first reference_id from the returned set in array.
The best way to tackle this would be to use if (in_array(5, $result)) where 5 is the needle and $result is the array haystack.
Because all you are doing is to check if the reference exists in the returned data set .
This is also good design practices, to collect results and avoid multiple reference queries each time, hit the database once and query the result set.
If its a multidemnsional array loop through the set:
foreach($result as $resultItem)
{
if(in_array("reference_id", $resultItem, true))
{
echo "There is Data";
}
}
Good Luck .
I am having a really odd problem here, in that I can replace a record but cant create new ones for some reason. If I create an album with id = 2hdfhh4 and then submit an album with the same id the details get updated. If I try posting a new album nothing happens, I don't even get any errors either ?.
include("connect.php");
$photostring = implode(',',$photos);
$albumname = htmlspecialchars($albumname);
$sqlA = <<<SQL
SELECT *
FROM `albumorders`
WHERE albumid = '$albumid'
LIMIT 1
SQL;
if(!$resultA = $db->query($sqlA)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowA = $resultA->fetch_assoc()){
if ($albumid = $rowA['albumid']){
mysqli_query($db,"UPDATE albumorders SET `albumid`='$albumid',`albumname`='$albumname',`imagesordered`='$photostring' WHERE `albumid`='$albumid'");
}
else {
mysqli_query($db,"INSERT INTO albumorders (`albumid`,`albumname`,`imagesordered`) VALUES ('$albumid','$albumname','$photostring')");
}
}
My table looks like this :
if ($albumid = $rowA['albumid']){
is an assignment, so it always evaluates to true and you won't get to the else part.
It should be:
if ($albumid == $rowA['albumid']) {
Here you are double checking the value.
The SQL Query will check whether the row with $albumid is available or not.
So, what you can do is you can directly check the sql result. If sql result is avaiable you update the row else you insert into data into the table...
I want to update some entries in my database, basically I am counting the number of checkboxes that have been selected on the previous page and multiplying them with 25 then adding that value to the current value in the DB.
This is my code:
<?php
if($_POST['code_approve'])
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$approval_id = $checkbox[$i];
$checkboxCount = count($_POST['checkbox']);
$countx25 = $checkboxCount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
$result2 = mysql_query($sql2);
$result = mysql_query($sql);
}
if($result)
{
echo "$countx25";
}
}
?>
It seems, that for some reason it is multiplying $countx25 with the number of checkboxes before inserting it into MySQL. This if($result){echo "$countx25";}} always shows me the right value though.
If i select 1 it prints 25, 2 prints 50, 3 prints 75 and so on, but for the MySQL part, if i select 1 it adds 25 to current value, 2 adds 100, 3 adds 225 ?!
What's the error here ?
In your SQL query:
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
You don't tell the database which row to update, so all rows are updated. While you test, you first test once, then again and again, so it might add to fields you don't expect it to. Probably this is your problem.
To specify which row to update, use a WHERE clauseDocs.
To prevent updating the same field more than once, execute the query only once.
As I stated in my comment. You are running this for each checkbox you get via $_POST. Why do you even use the for loop if you use count to count the checkboxes. Remove the for loop and it will work as you intend it to.
The for loop in your code is the problem. I guess here you are trying to use all checkboxes in the previous page, for your code you loop for all the checkboxes, so if there are 4 checkboxes, the for loop will run 4 times. So please identify what you want to do.
This is your code.
<?php
if($_POST['code_approve'])
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$approval_id = $checkbox[$i];
$checkboxCount = count($_POST['checkbox']);
$countx25 = $checkboxCount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
$result2 = mysql_query($sql2);
$result = mysql_query($sql);
}
if($result)
{
echo "$countx25";
}
}
?>