Simple sample query working update but skips the first condition - php

I have a php code that updates the value in 2 tables and I used left join. It works but it keeps on skipping the first condition and always enters the second condition. I have no idea on mysql injection so please advice if my code is prone to mysql injection.
elseif ($_POST['check'])
{
if ($row[typeofdog] = 'Labrador')
{
$id = $_POST['data'];
$count = count($id);
for($i=0;$i<$count;$i++)
{
$sql = "UPDATE animals LEFT JOIN treats ON animals.style = treats.style SET animals.bone = bone - treats.total, treats.status = 'Approved' WHERE treats.id='$id[$i]'";
$result = mysql_query($sql);
}
if($result){header("location:login_success.php");}
}
else
{
$id = $_POST['data'];
$count = count($id);
for($i=0;$i<$count;$i++)
{
$sql = "UPDATE animals LEFT JOIN treats ON animals.style = treats.style SET animals.chunks = chunks - treats.total, treats.status = 'Approved' WHERE treats.id='$id[$i]'";
$result = mysql_query($sql);
}
if($result){header("location:login_success.php");}
}
}

First, = is for assignment. == is for comparison.
Second, using the index typeofdog without quotes is incorrect. PHP explains why here.
Try this:
if ($row['typeofdog'] == 'Labrador')
If this doesn't work, then $row['typeofdog'] does not equal 'Labrador'. In that case, try echoing $row['typeofdog'] just before the conditional so you can see what is being compared.
Also, yes, you are at risk for sql injection. First step to fixing this: don't use mysql. Instead use mysqli or pdo and utilize prepared statements.

Related

Update multiple rows with single query using MySQL and PHP

<?php
$userData = array();
while (anything to create a loop) {
$value1 = $result1_from_loop;
$value2 = $result2_from_loop;
$value3 = $result3_from_loop;
$userData[] = '("'.$value1.'", "'.$value2.'", "'.$value3.'")';
} // THIS ENDS THE WHLE OR FOR LOOP
$query = 'INSERT INTO users (data1,data2,data3) VALUES' . implode(',', $userData);
mysql_query($query);
?>
The above code works perfectly for inserting multiple records into table users as seen above and it's very fast as well.
However, I am trying to use the same method to update after going through a loop as before. I have no idea how to achieve this.
I want something like this:
<?php
$userData = array();
while (Loop statement) {
$value1 = $result1_from_loop;
$value2 = $result2_from_loop;
$value3 = $result3_from_loop;
$userData[] = '("'.$value1.'", "'.$value2.'", "'.$value3.'")';
} // This ends the WHLE or FOR loop
$query = 'UPDATE users SET(data1,data2,data3) VALUES' . implode(',',$userData) WHERE data2=$value2
mysql_query($query);
I know the above code is not close to correct, syntax is even wrong. I just pasted it to show the idea of what I want achieved. In the WHERE statement how will data2 get to know the value of each $value2?
UPDATE uses a different format to INSERT. For UPDATE, your code should look something like this:
$query = 'UPDATE users SET data1 = $userData[0], data2 = $userData[1], data3 = $userData[2] WHERE data2=$value2';
Although just as a note, using mysql_query is not advised as it is deprecated (and will be removed altogether in later PHP versions) and your code is vulnerable to SQL injection. At a minimum I'd recommend using mysqli_query instead and looking into using prepared statements.

update array data to database inside looping

I face a problem with update more then one value with the same name to database.
//while loop
{
<input name="exists[]" value='$row1[Status_Name]'></input>
}
bellow are how I update the data to database
if (isset($_POST["updsts"]))
{
$gid = $_POST["id"];
$sqlq = "SELECT * FROM orderstatus WHERE Status_Group = '$gid'";
$result = mysqli_query($conn, $sqlq);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0)
echo "No records found";
else
{
$x = '0';
while( $x<$rowcount)
{
$stsname = $_POST["exists[$x]"];
$sqlu = "UPDATE orderstatus SET
Status_Name = '$stsname'
WHERE Status_Group = '$gid'";
$x++;
}
}
My $row1[Status_Name] will show all the status_name inside a table.
You can loop over the post array key:
foreach ($_POST['exists'] as $val) {
// Do your updates here
}
Additionally, this code has a lot of other serious problems you should be aware of.
You're not escaping any data used in the context of HTML. Use htmlspecialchars() around any arbitrary data you're concatenating into HTML. Without this, you risk creating invalid HTML as well as potential security issues with injected scripts.
You're not escaping any data used in your queries! As it stands right now, pretty much anyone can do whatever they want with your database data. Automated bots hit these sort of scripts and exploit them all the time. Use parameterized queries, always. Never concatenate data into the context of a query!
There's no need for this select and then update loop. Just use one update.

Update database with php is not working

i have a form to update informations about a product. the form gets the values from the database and sends it to the page that should update the database. i checked that form sends the values to the second page correctly. but the update function of database is not updating.
the code of the update (second) page is like that:
include("database.php");
if (isset($_REQUEST["kullanici"])) {
include "database.php";
$sql = ("select * from uye");
}
else {
header ("Location: uyari.html");
}
$id = $_POST['id'];
$urunadi = $_POST['urunadi'];
$malzemekodu = $_POST['malzemekodu'];
$urunkategorisi = $_POST['urunkategorisi'];
$birim = $_POST['birim'];
$miktar = $_POST['miktar'];
$personel = $_POST['personel'];
$birimfiyat = $_POST['birimfiyat'];
$fiyatbirimi = $_POST['fiyatbirimi'];
$resim = $_POST['resim'];
$sql = ("UPDATE depo SET id = $id, urunadi = $urunadi, malzemekodu = $malzemekodu, urunkategorisi = $urunkategorisi, birim = $birim, miktar = $miktar, personel = $personel, birimfiyat = $birimfiyat, fiyatbirimi = $fiyatbirimi, resim = $resim WHERE id = $id");
$kayit = mysql_query($sql);
if (isset ($kayit)){
echo "Stok Kaydınız Yapılmıştır.";
}
else {
echo "Stok Kayıt Başarısız.";
}
how could i solve this problem?
query variable should be quoted try change update query to
$sql = ("UPDATE depo SET id = '$id', urunadi = '$urunadi', malzemekodu = '$malzemekodu', urunkategorisi = '$urunkategorisi', birim = '$birim', miktar = '$miktar', personel = '$personel', birimfiyat = '$birimfiyat', fiyatbirimi = '$fiyatbirimi', resim = '$resim' WHERE id = '$id'");
If still issue check your post data is getting on this page Also use mysql_real_escape_string() to escape your post data
Note :- mysql_* has been deprecated use mysqli_* or PDO
You must add quotes around the fields when updating / inserting strings. The same applies to date fields.
Also you should format all strings with mysql_real_escape_string() as this prevents hackers being able to attack your database by passing SQL in the string. For integers and floats you should use intval() and floatval() for the same reason.
Lastly, you should also length cut a string to the text length of the string field, in PHP use substr(). This prevents an error if the string length is longer than the field allows (some older browsers don't support lengthcut).
$personel = mysql_real_escape_string(substr($_POST['personel'], 0, 45)); // 45 = string length
$id = intval($_POST['id']);
Try using mysqli instead of mysql (depreciated) in PHP, you can also use PDO, however PDO is not as comprehensive and upto date as MYSQLI, and due to this is slightly slower. The only advantage of PDO over MYSQLI is that PDO also works with PostgeSQL, so switching database engine is easier, however the SQL between MYSQL and PostreSQL differ slightly, so it's not that easy.

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.

Problem with MySQL query

I'm trying to debug a MySQL query, and I have trouble understanding why one while loop in my script is not working:
// select db
mysql_select_db($dbname);
for ( $x = $latRange[0]; $x <= $latRange[1]; $x++ )
{
for ( $y = $lngRange[0]; $y <= $lngRange[1]; $y++)
{
$sql="SELECT * FROM $usertable WHERE $xlookup = $x AND $ylookup = $y";
$SQLresult = mysql_query($sql);
while( $row = mysql_fetch_array($SQLresult) )
{
$tmpResult = $row[$popDen];
$result += $tmpResult;
}
}
}
Sample values of the variables described are:
$latRange = array(3,7);
$lngRange = array(9,25);
$popDen = 'ColumnNameIWant'
$xlookup = 'Col1'
$xlookup = 'Col2'
The logic behind my query is that it finds all combinations of x and y, gets the corresponding $popDen value, and adds it to $result. Result is defined at the start of my script, and returned by the program after this loop.
I know that the problem section is my while loop, but I don't quite understand how to fix it as I don't fully understand how mysql_fetch_array functions. I've also tried mysql_fetch_row and my query does not work with this either.
I know from commenting out various chunks of the code, and passing back other numbers that everything else works; it is just this chunk that is failing.
Are there any obvious errors that I am making?
If popDen is a column in your table, you need to get it with:
$tmpResult = $row['popDen'];
and if it is the only value you need, you can simplify / speed up your sql query:
$sql="SELECT `popDen` FROM $usertable WHERE $xlookup = $i AND $ylookup = $y";
Edit: By the way, you might want to initialize your $result variable so that it has a defined / valid / known value if no rows are found.
One obvious error is to use dynamic table names.
This leaves hard to close SQL-injection holes:
Use this code to plug that hole, because mysql-real_escape_string() will not help!
$allowed_tables = array('table1', 'table2');
$clas = $_POST['clas'];
if (in_array($clas, $allowed_tables)) {
$query = "SELECT * FROM `$clas`";
}
See here for more info: How to prevent SQL injection with dynamic tablenames?
And don't forget to always enclose dynamic tablenames in backticks ` or your code will break if you happen to use a reserved word or a number for a table or column name.

Categories