Why is this not updating the DB? - php

It out puts the the results of the equation but dose not update the DB?? I have another connection open in the code at this point via mysql...
<?php
if($user_new=='Yes'){
$end = strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')) - 1;
$now = time();
$time = $end - $now;//Seconds til end of month
$percent = $time / 2635200;
$minus_1 = 1 - $percent;
$server = 'XXXXXXX';
$user = 'XXXXXXX';
$pass = 'XXXXXXXX';
$db = 'XXXXXXX';
$con = mysqli_connect ($server, $user, $pass, $db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_ID = get_current_user_id();
mysqli_query($con,"UPDATE usermeta SET value=$minus_1
WHERE user_id='$user_ID' AND meta_key='user_new_mo'");
$user_per = $global_bal * $minus_1;//2635200 = Seconds in 30.5 days
$minus_per = $global_bal - $user_per;
$echo = $minus_per * $user_ghs;
}
elseif($user_new>='0'){
$num_result = mysql_query("SELECT value FROM usermeta WHERE user_id='$user_ID' AND meta_key='user_new_mo'", $hash_con);
$echo = $num_result;
}

Try a prepared statement to help with variable substitution.
$stmt = $mysqli->prepare("UPDATE usermeta SET value=? WHERE user_id=? AND meta_key=?");
$stmt->bind_param($minus_1,$user_ID,'user_new_mo');
$stmt->execute();
$stmt->close();

In mysql query you must want to differ the php variables and the string like this Eg.
mysql_query($con,"select * from users where userid='".$user_id."'")
For eg the if $user_id=ssoft then the query resembles like this,
select * from userid where userid='ssoft'.
IAM SURE IT WILL HELP YOU.

Let's assume first that you have no mysql errors (I see you're not checking that in your code)... Most probably your update problem (not updating) should have something to do with the $user_ID.
Check to make sure that "get_current_user_id()" returns a value that exists in the [user_id] column in your table.
Next... If the "get_current_user_id()" isn't the problem, then the problem is in your query (I think this is most probable): whenever you have to deal with variables inside a string, use curly braces.
So, turn
WHERE user_id='$user_ID'
into
WHERE user_id='{$user_ID}'
Or simply concatenate it like:
$query = "SELECT * FROM `x` WHERE `some_column` = '" . $someValue . "'";
Use of curly braces for variables inside a string is valid only if the string is wrapped in double quotes (your's is, so you're ok here), otherwise $someVar is simply the string $someVar (ie $string = '$someVar') as opposed to $someVar = 'abc'; $string = "{$someVar}"; - then $string becomes abc
Also, this being an integer (I suppose) there would be no need for the quotes, but it should still work (unlike the other way around, if you would want to enter a string without quotes).

Related

Pass a PHP string in to SQL with multiple values?

I have a situation in some really old code of mine where I am trying to pass through the data from a string and do a DB query off of those values.
The data loads correctly if I set $hula = '7630' but when I set it to multiple values in a string like $hula = '7890, 5630' I get error (Message: db2_execute(): Statement Execute Failed)
I clearly know I am missing something here but I am CLEARLY not seeing it. Thanks
<?php
$hula = '7890, 5630';
$stmt = "SELECT TXLCT2, ZFDLDS FROM ".$ArEnviro>getDataLibFin().".TXPL6C2, ".
$ArEnviro->getDataLibFin().".HXPTABLD WHERE TXLCT2 = CFDECD AND CFDTCD = 'YCT2' AND TXLLV6 IN ? ORDER BY TXLCT2";
$preparedStmt = db_prepare($ArConnections->getDB2ConnResource(),$stmt);
$result = db_execute($preparedStmt, [$hula]);
while(($row = db_fetch_both($preparedStmt)) == true) {
echo('<option value="'.htmlspecialchars($row["TXLCT2"]).'">'.htmlspecialchars($row["TXLCT2"]).' - '.htmlspecialchars($row["ZFDLDS"]).'</option>');
}
?>
A simple change:
if TXLLV6 is integer:
$hula = '(7890, 5630)';
If it is varchar or any kind of string:
$hula = "('7890', '5630')";

PHP Adding values to an array using while(mysql_fetch_array)?

I'm trying to add values to an array after getting data from a mysql query, this obviously involved a while ($x = mysql_fetch_array($MysqlQuery)) {} as seen below:
$CheckTime = mysql_query("SELECT * FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysql_fetch_array($CheckTime)) {
$DateInt = strtotime($date['Date']);
//echo $DateInt . " ";
$dates[] = $DateInt;
echo $dates[1] . " ";
}
However when I echo $dates[x], it'll display the value in the x position of the array, but it'll show it by (x+1) times (i.e. $dates[0] will show 'a' once, $dates[1] will show 'b' twice, and $dates[2] will show 'c' thrice)
How do I fix this? What's causing the problem?
$CheckTime = mysqli_query($mysql_connection, "SELECT * FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysqli_fetch_assoc()($CheckTime)){ // Use mysqli_* for queries.
$DateInt = strtotime($date['Date']); // This will show an UNIX timestamp
$dates[] = $DateInt; // Fills the array with the timestamp.
}
Your problem is that you use mysql_fetch_array. But then try to use $date['Date']. If you want to use the column names as indices in the $date array. You need to use mysql_fetch_assoc().
On a different note and as mentioned in the comments use the mysqli_* extension or PDO. In this answer I've used mysqli_*
Please note the $mysql_connection in the mysqli_query function.
MySqli Query Doc
Most likely if you use the code below it should work as intended.
Still strongly advise to switch to mysqli_*
$CheckTime = mysql_query("SELECT Date FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysql_fetch_array($CheckTime)){
$DateInt = strtotime($date[0]);
$dates[] = $DateInt;
}
foreach($dates as $timestamp){
echo $timestamp . '<br/>';
}
This works, make sure to put in your correct credentials to connecting to your database on step #1. everything else false in place.
<?php
/* ==============================================
This is the new way of connecting to database
using mysqli
================================================*/
// Step #1 create credentiasl for database connection
$host = ""; //type your host ex. localhost between the quotes
$user = ""; //your username between the quotes
$pass = ""; //your password between the quotes
$db = ""; //your database you are connecting to between the quotes
// step #2 create connection to database
$conn = new mysqli($host, $user, $pass, $db);
//step #3 check and see if connection is working and error free
if ($conn->error) {
die("Could not connect to the database");
} else{
// create array dates
$dates = array();
// create select statement
$CheckTime = ("SELECT * FROM cp11641_timetable.booking");
// query the the database using the connection
$sql_CheckTime = $conn->query($CheckTime);
// if rows available in table add them to array dates
while ($row = mysqli_fetch_assoc($sql_CheckTime)) {
$dates[] = $row;
}
//optional uncomment bottom line to check if dates array has data will display as array on webpage
// var_dump($dates);
// loop through array
foreach ($dates as $date){
// echo out data you want to display. 'Date' = column name
echo strtotime($date['Date']) . "<br>";
};
};
?>
I recommend you to using mysql_fetch_assoc() and then display the dates horizontally or vertically with html/css style.
Sorry if my answer is bad choose.

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 save html-code in phpmyadmin

I have a little problem to save html-code in phpmyadmin.
Thats the html-code ($html_txt) which I would like to save in the sql-table. I get the code from an other sql-query.
An günstigen Tagen "Paradies" ist es dienlich.
Test/Test<br /><br />"Test"
And that is my query.
$id = 1;
$html = "'".$html_txt"'";
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
That does not work. Any idea? I tried it also like this:
$id = 1;
$html_txt;
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
You must escape the string statements before querying. Your query should be like the following:
$con = mysqli_connect("localhost","user","password","db");
$id = mysqli_real_escape_string($con, $id);
$html_txt = mysqli_real_escape_string($con, $html_txt);
$sql = 'UPDATE table SET text = ' . $html_txt . ' WHERE id = ' . $id . '';
I die if I do not say:
Please use parameterized query
Please avoid using vulnerable sql statements.
use mysql_escape_string to support for html entities and may the text be the kwyword so use like this text
$id = 1;
$html =mysql_real_escape_string($html_txt);
$sql = 'UPDATE table SET `text` = '.$html.' WHERE id = '.$id.'';
This should be a comment - but it's a bit verbose.
It should be obvious to most PHP developers that the problem is lack of escaping of the HTML string, however that in itself is not a reason for this being a poor question.
You've not provided details of any attempt to investigate the problem yourself. "Doesn't work" is not a good description of what happenned - in this case the expected outcome is fairly obvious to me, but that's not always the case. I aslo know what the actual outcome would be - but you've not documented that either. In most occassions where code does not behave as expected, an error message will be reported somewhere - you should be looking for it. The DBMS would have returned a specific error message - which your code should poll - especially if you are running into problems.
If you had viewed the SQL you were sending (or included it in your post) this would also have helped diagnosis.
You should properly escape your HTML value. Though this solution is not optimal as it does not use parameterized queries (PDO, ....), try this:
$html = 'An günstigen Tagen "Paradies" ist es dienlich. Test/Test<br /><br />"Test"';
$id = 1;
$sql = 'UPDATE table SET text = '.mysql_real_escape_string($html).' WHERE id = '.$id.'';
i would suggest you use mySQli prepared statement, WHY : i think somewhere along the line your variable have funny characters that r messing up with your query..with prepared statements the query is send alone then after your variables are binded to it, pls check above code
$conn = new mysqli("localhost", "your username", "your pass", "your db");
$myString = "Your string here";
$id = 1;
$insertDB = $conn->prepare("UPDATE table SET text = ? WHERE id = ?");
$insertDB->bind_param('si', $myString, $id); //bind data, type string and int 'si'
$insertDB->execute(); //execute your query
$conn->close(); //close connection

Building interactive WHERE clause for Postgresql queries from PHP

I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.

Categories