Pass sql variable into PHP variable then back into sql statement - php

I want to select the highest value in a table:
$max = "SELECT MAX(pid) FROM pic";
Then pass that value into a PHP variable:
$results_max = $conn->query($max);
$highest_val = $results_max->fetch_assoc();
To then use again in a SQL insert statement:
$sql_update = "UPDATE users
SET username = '$username', pid = '$highest_val'
WHERE username = '$username'";
However i tested out the value i got from my first select statement ($highest_val) and it returns "Array". Does anyone know what I am doing wrong?
Edit:
$sql_update = "UPDATE users
SET username = '$username', pic_id = '$highest_val[pid]'
WHERE username = '$username'" ;

You need to create alias of MAX(pid);
$max = "SELECT MAX(pid) as pid FROM pic";
Now you fetch max pid using
$results_max = $conn->query($max);
$highest = $results_max->fetch_assoc();
$highest_val =$highest['pid'];// pass column name here
And your Update query would be
$sql_update = "UPDATE users
SET username = '".$username."', pid = '".$highest_val."'
WHERE username = '".$username."'";

Related

how to get max value of a sql database query in php

I want to find out the max value of sql data column on the basis of email id and username. (there is no primary entity)
To get the email id, i store the user email id from session.
here goes my code:
$emailid = $userRow['emailid'];
$sql = "select max(item) from product where email = '$emailid' AND username = 'arun'";
$result = $conn-> query($sql);
$row = $result->fetch_assoc();
echo "Max item : " .$row['result'];
It's giving me first value of sql table but not highest.
you can either change your column data-type or use CAST or CONVERT.
$sql = "SELECT MAX( CAST( `item` AS UNSIGNED) ) as max FROM `product` WHERE `email` = '$emailid' AND `username` = 'arun'";
If possible its better to change the data-type.
Try this,
$emailid = $userRow['emailid'];
$sql = "SELECT MAX(item) AS item FROM product WHERE email = '$emailid' AND username = 'arun'";
$result = $conn-> query($sql);
$row = $result->fetch_assoc();
echo "Max item : " .$row['item'];
Try this way,
$rowSQL = mysql_query( "SELECT MAX( ID ) AS max FROM `tableName`;" );
$row = mysql_fetch_array( $rowSQL );
$largestNumber = $row['max'];

update table for multiple users

I am looking to count the number of times 'yes' in present for a user in a table, then post the result into anther table for that same user. Both tables have the username. I would like this done for each user. I have the following but it is not working.
$sql = $item_count = "SELECT SUM(if(strike='yes',1,0)) AS strike_total FROM weekpicks WHERE username = 'username'";
// execute SQL query and get result
$sql_result = mysql_query($sql) or die (mysql_error());
if (!$sql_result) {
echo "Something has gone wrong!";
}
else {
//loop through record and get values
while ($row = mysql_fetch_array($sql_result)) {
$item_result = ($row = #mysql_query($item_count)) or die(mysql_error());
$strike_total = ($row = #mysql_result($item_result,"strike_total"));
$strikes = ($row = $strike_total ['strike_total']);
$username = $row["username"];
// the following will insert number of strikes into table for each user.
$sql = "UPDATE authorize SET strikes = '($strikes)' WHERE username='$username'";
//mysql_query(" UPDATE authorize SET " . "strikes = '" . ($strikes) . "' WHERE username='$username' ");
$result = mysql_query($sql) or die (mysql_error());
Just one query should be enough
Update for single user..
UPDATE authorize SET strikes = (select count(*) from weekpicks WHERE username = '$username' and strike='yes') WHERE username='$username';
For bulk update all users
UPDATE authorize as A SET strikes = (select count(*) from weekpicks B WHERE strike='yes' and A.username=B.username group by B.username)
Isn't that simple.

My MySQLi dosen't update only inserts? What's wrong with my script?

$check_verified_user = mysqli_query("SELECT * from user_verified where user_mail = '$payer_email'");
$user_verified = mysqli_fetch_array(mysqli_query($conDB, "SELECT * FROM user_verified where user_mail = '$payer_email'"));
if(mysqli_num_rows($check_verified_user) > 0) {
mysqli_query($conDB, "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'");
} else {
mysqli_query($conDB, "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')");
}
I don't know what's wrong with my script, it checks if the row exists, then if it exists it should update, but instead it inserts another row, which i don't understand...
Give this a try.
$query = "SELECT * FROM user_verified WHERE user_mail = $payer_email";
$check_verified_user = mysqli_query($conDB, $query);
You basically wasn't giving it the database connection, so it was always coming back as not being greater than 0 rows. Personally, I always put my query into its own variable first, and this will ensure that you don't forget params for the mysqli_query() function. It also makes it easier to read, and allows you to use the query in other places if needed.
You can do this method:
$sql = "SELECT * from user_verified where user_mail = '$payer_email'";
$result = mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
if (mysqli_num_rows($result)) {
$sql = "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'";
}
else {
$sql = "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')";
}
mysqli_free_result($result);
mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
If your user_mail is a UNIQUE KEY you would be able to use the option ON DUPLICATE KEY UPDATE in the INSERT. You can do everything in just 1 query.
$sql = "INSERT INTO user_verified (user_mail,total_paid) VALUES ('$payer_email',$payment_amount) ON DUPLICATE KEY UPDATE total_paid = total_paid + $payment_amount";
mysqli_query($conDB, $sql);
Check this example of a table using UNIQUE KEY.
http://sqlfiddle.com/#!2/4919e2/1/0

I can't figure out how to update my last inlog time

I'm trying to make an last activity function for an website. but i can't get it to work. I hope you guys can help me out here.
this is my query:
$last_activity_query = "UPDATE users_table SET user_name = '$user_name' WHERE 'date_last_inlog' = NOW()";
$result_update = mysql_query($last_activity_query);
$last_activity_update = mysql_fetch_array($result_update);
this is an print screen of my database table:
I want to store this update in the last row.
Thanks in advance!
i've changed my script now but its still not changing anything in my database table.
this is the change:
if (isset($_REQUEST['inlog_submit'])){//checks if form is submitted
$user_name = $_REQUEST['username_input'];//request username from inlog_form
$password = $crypt;//gets enqrypted pass
//$tbl_name="user_table"; // Table name
$query = "SELECT * FROM users_table WHERE user_name= '$user_name' AND password='$password'";//query stored in var
$last_activity_query = "UPDATE users_table SET 'date_last_inlog' = NOW() WHERE user_name = '$user_name'";
$result = mysql_query($query);//var with result of query
$result_update = mysql_query($last_activity_query);
if ($user_name = mysql_fetch_array($result)){//checks inlog data from form with the $result query
$_SESSION['user_name'] = $user_name[user_name];//creates session with username
$_SESSION['password'] = $password[password];//creates session with password
$last_activity_update = mysql_fetch_array($result_update);
header ('Location: admin.php');//when login is correct redirect to specified page
}else{
$error_inlog = 10;//when inlog data is incorrect this error will show
}
}
?>
Your SQL query is in the wrong order.
$last_activity_query = "UPDATE users_table SET 'date_last_inlog' = NOW() WHERE user_name = '$user_name'";
Your logic is incorrect. Use this:-
"UPDATE users_table SET 'date_last_inlog' = NOW() WHERE user_name = '$user_name'";
You are using this :-
UPDATE users_table SET user_name = '$user_name' WHERE 'date_last_inlog' = NOW()
You are trying to update user_name column where the date_last_inlog column value is equal to the current time which is logically incorrect.

Issue updating values in Database from mySQL query on PHP site

Been tinkering with my website, it is a seat booking website. Still in alpha testing really so not live to the public yet for obvious reasons.
However, I'm having a few problems with updating the values in my database.
I'll post the code and then explain the problem..
else {
$seatID = $_POST['form_submitted'];
$query1 = "SELECT seatTaken FROM SEATS WHERE seatNo = '$seatID'";
$result = mysql_query($query1);
while($row = mysql_fetch_array($result))
{
$taken = $row['seatTaken'];
}
$query2 = "SELECT passNo FROM PASSENGER WHERE username = '$loggedinuser'";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
$passno = $row['passNo'];
}
$query3 = "SELECT groupID FROM PASSENGER WHERE username = '$loggedinuser'";
$result = mysql_query($query3);
while($row = mysql_fetch_array($result))
{
$groupno = $row['groupID'];
}
$query4 = "SELECT flightNo FROM PASSENGER WHERE username = '$loggedinuser'";
$result = mysql_query($query3);
while($row = mysql_fetch_array($result))
{
$flightno = $row['flightNo'];
}
// if ($taken = 0) {
$update = mysql_query("UPDATE PASSENGER SET seatNo = $seatID WHERE username = '$loggedinuser'");
$update2 = mysql_query("UPDATE SEATS SET seatTaken = 1, passNo = '$passNo', groupID = '$groupid' WHERE seatNo = '$seatID'");
// AND flightNo = '$flightno'"
echo '<meta http-equiv="refresh" content="5;url=http://www.mywebsite.com/">';
echo mysql_error();
//}
}
?>
Now the user will have selected their seat in the previous form hence the:
$seatID = $_POST['form_submitted'];
However, at the bottom in my queries, the only value that actually changes in the database when this PHP code is run is the boolean value of 'seatTaken', in that it does change from 0 (not occupied) to 1 (occupied).
The field passNo and groupID in my database DO NOT UPDATE as referenced here in these queries:-
$update = mysql_query("UPDATE PASSENGER SET seatNo = $seatID WHERE username = '$loggedinuser'");
$update2 = mysql_query("UPDATE SEATS SET seatTaken = 1, passNo = '$passNo', groupID = '$groupid' WHERE seatNo = '$seatID'");
Is anyone able to help? Many thanks!
Tom
Watch your variable naming and string quotation
When your looking for values in mysql, they usually need to be a string literal (add quotes).
And your other problem is your variable names:
$update = mysql_query("UPDATE PASSENGER SET seatNo = '$seatID' WHERE username = '$loggedinuser'");
$update2 = mysql_query("UPDATE SEATS SET seatTaken = 1, passNo = '$passno', groupID = '$groupno' WHERE seatNo = '$seatID'");
$passno vs $passNo
$groupid vs $groupno
You should also make sure you properly escape any input coming from the user http://php.net/manual/en/function.mysql-real-escape-string.php
One can't see in your code how do you generate the values of $groupid, $passNo, $seatID. Are those varaibles set when you do your update? (just echo the SQL code to see what query is being sent to your database)
Maybe you should try getting the variables from your post request, like $_POST['groupid'], if groupid is the name of the field in the form.

Categories