Checking with PHP should table update should be done - php

Hi to all of you programmers. I want disable table update in my database if inputted value is lower than value in db. The code looks ok, but update always executes. This is my code:
$sql="UPDATE student SET _id_year='$_year' WHERE _index='$_index'";
$check1="SELECT _id_year FROM student WHERE _index='$_index'";
if('$_year'>'$check1')
{
mysqli_query($con,$sql);
}
Note: _id_year and _index are values from DB, and $_year,$_index are inputted values.
$con is connection to database.

First execute your select query and get $check1. Then compare.
$qry = "SELECT _id_year FROM student WHERE _index='$_index'";
$exec = mysqli_query($con,$qry);
$result = mysqli_fetch_object($result);
$check1 = $result->_id_year ;
Also, you Don't have use single quotes. Try this,
if($_year > $check1)
{
mysqli_query($con,$sql);
}

Using SafeMysql the code would be almost the same as you wrote, but it will actually run these queries and also make it safe:
$check=$db->getOne("SELECT _id_year FROM student WHERE _index=?s",$_index);
if($_year > $check )
{
$db->query("UPDATE student SET _id_year=?s WHERE _index=?s",$_year,$_index);
}

You should execute the $check1 query first, get it's result, then compare it with you $_year variable

It is always true because of the quoted field of your PHP it should not be qouted
if($_year>$check1)
{
mysqli_query($con,$sql);
}

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

php app to verify login

Trying to understand how to process a form in php that logs in. It seems clumsy, hopefully there is a better way.
Let's say the user login is userid and password.
If they enter the information on the form, I jump to the next page:
<?php
if (isset($_POST["id"])) {
$con=mysqli_connect("localhost","user","pw","db");
$codeFile = $_POST["filename"];
$id = $_POST["id"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$res = mysqli_query($con, "SELECT COUNT(*) from users where id='$id' and fname='$fname' and lname='$lname'");
$row = mysqli_fetch_array($res);
$count = $row[1];
if ($count == 1) {
header("submit.php");
die();
}
$res = $con->query('INSERT INTO log values ($id, now(), $codeFile)');
}
?>
The above code should theoretically only jump to submit.php if exactly one row comes back because there is a matching user. It does not seem to work.
how do I request the first column back? It has no name because it is not a named column.
I cannot believe how many statements it takes to get one simple query done, is there any better way in PHP? Java servlets has some nifty shortcuts such as an integer return code with the number of affected lines, among other things.
if this works, I want to do an insert. It would of course be better to do a combined statement and base the test on the number of lines inserted (1 or 0)
$res = $con->query('INSERT INTO log values ($id, now(), $codeFile)');
Is there any way of combining this into a single query that returns true if it succeeds?
I suggest you either use SELECT * or the actual columns themselves instead of COUNT(*)
For example: SELECT id,fname,lname from table
Yet, I suggest you go about it this way:
Instead of:
$row = mysqli_fetch_array($res); $count = $row[1];
do:
$count = mysqli_num_rows($res); if($count==1){...}
For example and adding mysqli_real_escape_string() for added security (more under Footnotes below)
Sidenote: I'm under the impression that if the query doesn't meet the criteria, that you would like users to be redirected to submit.php and if it does meet it, to do an INSERT.
If so, I modified the method. Plus, using header("submit.php"); is incorrect.
The proper way is header("Location: http://www.example.com");
Another thing before passing on to the code.
This line should use quotes around the values and double quotes to wrap it with:
$res = $con->query('INSERT INTO log values ($id, now(), $codeFile)');
as in:
$res = $con->query("INSERT INTO log values ('$id', now(), '$codeFile')");
NOTE: Try and use actual columns to insert into, it's better.
Plus, $res will not execute since there is no condition set to it. Either remove $res = or add
if($res){
echo "DB insertion was successful.";
}
The code:
<?php
if (isset($_POST["id"])) {
$con=mysqli_connect("localhost","user","pw","db");
$codeFile = mysqli_real_escape_string($con,$_POST["filename"]);
$id = mysqli_real_escape_string($con,$_POST["id"]);
$fname = mysqli_real_escape_string($con,$_POST["fname"]);
$lname = mysqli_real_escape_string($con,$_POST["lname"]);
$res = mysqli_query($con, "SELECT * from users WHERE fname='$fname' AND lname='$lname' AND id='$id'");
$count = mysqli_num_rows($res);
// if successful login, INSERT INTO...
if ($count == 1) {
// NOTE: Try and use actual columns to insert into, it's better.
$res = $con->query("INSERT INTO log values ('$id', now(), '$codeFile')");
if($res){
echo "DB insertion was successful.";
}
}
// if not successful, redirect.
else {
header("Location: submit.php");
exit();
}
} // end brace for (isset($_POST["id"]))
?>
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO
Passwords
I noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Other links:
PBKDF2 For PHP
You can use the mysqli->affected rows :
http://us1.php.net/manual/en/mysqli.affected-rows.php
you can use LIMIT in your query to return only one result, although it's bad practice if you're getting back a login query, there should be only one anyway.
as to why your code doesn't work, It's hard to say, it depends what comes back from your database.
You'll need to debug $count and see what actually comes out, and work from there.
Finalyl, as far as I know it's not possible to run two queries on the same line, You'll need two inserts for two tables.(table log and table value)

Updating MySQL DB with PHP

I'm using foreach to loop an array and update a MySQL database.
This is my code
foreach($result['getHiscore'] as $highScoreType => $highScoreValues){
$rank = $highScoreValues['rank'];
$lvl = $highScoreValues['lvl'];
$totalXp = $highScoreValues['totalxp'];
mysqli_query($con,"UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp,
WHERE UserID= '1'");
}
i'm trying to conflate the word "level" with the contents of $highScoreType, the column titles in my DB are Leveloverall, Xpoverall, Levelattack, Xpattack and so on so i was planning on keeping the Level/Xp title constant and just changing the key.
This looks fine to me and when i tested the sql with pre-set values it updated fine, however using the variables doesn't update at all. I know that the variables are coming out of the array correctly as when i echo them inline with the foreach they print out in the correct format and order.
Is it my formatting thats the issue or am i doing missing something else?
If you echo the generated SQL query that should help you see any problems in the query.
It looks odd to me: UPDATE Users SET Level("$highScoreType") = $lvl
Shouldn't that just be UPDATE Users SET $highScoreType = $lvl ?
Be aware also that this sort of code is vulnerably to SQL injection attacks so always be wary of what could be in those variables.
To print the query do:
$query = "UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp, WHERE UserID= '1'"
echo $query
mysqli_query($con, $query)

php request of mysql query timeout

i'm trying to make a long mysql query and process and update the row founded:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result))
{
//process row
}
but after 60 second give me a timeout request, i have try to insert these in my php code:
set_time_limit(400);
but it's the same, how i can do?
EDIT:
only the query:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
takes 2-3 second to perform, so i think the problem is when in php i iterate all the result to insert to row or update it, so i think the problem is in the php, how i can change the timeout?
EDIT:
here is the complete code, i don't think is a problem here in the code...
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result)) {
//print $db_row['id_show']."-".$db_row['actors']."<BR>";
$explode = explode("|", $db_row['actors']);
foreach ($explode as $value) {
if ($value != "") {
$checkactor = mysql_query(sprintf("SELECT id_actor,name FROM actors WHERE name = '%s'",mysql_real_escape_string($value))) or die(mysql_error());
if (mysql_num_rows($checkactor) != 0) {
$actorrow = mysql_fetch_row($checkactor);
$checkrole = mysql_query(sprintf("SELECT id_show,id_actor FROM actor_role WHERE id_show = %d AND id_actor = %d",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
if (mysql_num_rows($checkrole) == 0) {
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor) VALUES (%d, %d)",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
}
} else {
$insertactor = mysql_query(sprintf("INSERT INTO actors (name) VALUES ('%s')",mysql_real_escape_string($value))) or die(mysql_error());
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor, role) VALUES (%d, %d,'')",$db_row['id_show'],mysql_insert_id())) or die(mysql_error());
}
}
}
}
Should definitely try what #rid suggested, and to execute the query on the server and see the results/duration to debug - if the query is not a simple one, construct it as you would in your PHP script, and only echo the SQL command, don't have to execute it, and just copy that in to the server MySQL command line or whichever tool you use.
If you have shell access, use the top command after running the above script again, and see if the MySQL demon server is spiking in resources to see if it really is the cause.
Can you also try a simpler query in place of the longer one? Like just a simple SELECT count(*) FROM tvshows and see if that also takes a long time to return a value?
Hope these suggestions help.
There are so many problems with your code.
Don't store multiple values in a single column. Your actors column is pipe-delimited text. This is a big no-no.
Use JOINs instead of additional queries. You can (or could, if the above weren't true) get all of this data in a single query.
All of your code can be done in a single query on the server. As I see it, it takes no input from the user and produces no output. It just updates a table. Why do this in PHP? Learn about INSERT...SELECT....
Here are some resources to get you started (from Googling, but hopefully they'll be good enough):
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
http://dev.mysql.com/doc/refman/5.1/en/join.html
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
What is Normalisation (or Normalization)?
Let me know if you have any further questions.

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

Categories