mysql table fields - Resource id #6 - php

I have a database (db_name=members) with a lot of fields but the relevant ones for this are:
security_question, security_answer, email
The php code is:
$email = $_COOKIE['site_user'];
$select_sa = mysql_query("SELECT security_answer FROM members WHERE email='".$email."'");
$result_sa = mysql_query($select_sa);
$arr_sa = mysql_fetch_row($result_sa);
$result2 = $arr_sa[0];
$get_sa = $result2;
If I
echo $select_sa;
It prints "Resource id #6" although in the table I can see the security answer as a word and not "Resource id #6".
If I
echo $get_sa;
It prints nothing.
Could you please help me to be able to read the securty_answer field from the database ?
Thanks,
Ray

You're doing the query twice, feeding the result handle from the first time into the query text parameter of the second one. That's invalid. Try this instead:
$select_sa = "SELECT security_answer FROM members WHERE email='".$email."'";
$result_sa = mysql_query($select_sa);
$arr_sa = mysql_fetch_row($result_sa);
$result2 = $arr_sa[0];
$get_sa = $result2;
Please also make sure that the $email field is being passed through mysql_real_escape_string() before being used in the query. All data fetched from the user, e.g. via $_GET, $_POST or $_COOKIE, must be escaped properly. If you don't escape it, you'll be open to SQL injection attacks.

Related

PHP posting a variable in a variable using mysql

I need to use the number of the district to be the tail end of my variable. Example $publish_page_ADD THE DISTRICT NUMBER
I am grabbing the $district_num from my url which I've verified with echo
Here is what I've tried
$district_num = $_REQUEST['district_num']; // from url and works
$publish_page_.''.$district_num = $district_var['publish_page_'.$district_num.'']; //this does not work
$publish_page_.''.$district_num = addslashes($_POST['publish_page_'.$district_num.'']); //this does not work
$sql = "UPDATE districts SET
publish_page_$district_num = '$publish_page_$district_num' //this does not work and throws error "can not find publish_page_ in field list
WHERE district_num ='$district_num'"; //this works when the above code is removed
Follow up on corrected code... Thank You #cale_b and #Bill Karwin
$district_num = (int) $_REQUEST['district_num'];
$$publish_page = "publish_page_{$district_num}";
$$publish_page = $district_var[ "publish_page_{$district_num}"];
if (isset($_POST['submitok'])):
$$publish_page = addslashes($_POST[$publish_page]);
$sql = "UPDATE districts SET
publish_page_{$district_num} = '$publish_page'
WHERE district_num ='$district_num'";
If you want to learn about PHP's variable variables, it's in the manual (I linked to it). But you actually don't need it in your case.
Be careful about SQL injection. Your code is vulnerable to it.
Since you're using input to form a SQL column name, you can't use SQL query parameters to solve it. But you can cast the input to an integer, which will protect against SQL injection in this case.
$district_num = (int) $_REQUEST['district_num'];
$publish_page_col = "publish_page_{$district_num}";
The above is safe because the (int) casting makes sure the num variable is only numeric. It isn't possible for it to contain any characters like ' or \ that could cause an SQL injection vulnerability.
For the other dynamic values, use query parameters.
$publish_page_value = $_REQUEST["publish_page_4{$district_num}"];
$sql = "UPDATE districts SET
`$publish_page_col` = ?
WHERE district_num = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([ $publish_page_value, $district_num ]);
As #cale_b comments below, you should understand that in PHP, variables can be expanded inside double-quoted strings. See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details on that.

Q: PostGreSQL How to Pass POST information in a SQL command more efficiently

I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.

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

PHP Using Get Post in WHERE function

On one page I have a form which POSTs the data entered in the 1 field across to another page.
On this page which you are directed to after entered data in the form field is a connection to a sql database. It happily rePOSTs the form field data on the page. Then I have got the PHP for retrieving the information from the database. This works nicely when the WHERE part is fixed manually ('criteria') however I would like the WHERE criteria for this search to be the form data from the previous page.
is there a way to echo the data to it? The form data is successfully getting to the displaying page however need help with the WHERE part.
That line of code currently is...
$result = mysqli_query($con,"SELECT * FROM table WHERE field = 'formdata'");
Any help would be appreciated greatly.
Right now, query compares field to the actual string 'formdata'. You'll want to grab the formdata, if you're POSTing, like this:
$result = mysqli_query($con, "SELECT * FROM table
WHERE field = '" . $_POST['formdata'] . "'");
Although, note that you'll need to use prepared statements to make this secure. See here and here.
I use PDO, but mysqli should be roughly the same
$formdata = $_POST['input'];
$stmt = $con->prepare('SELECT * FROM table WHERE field = ?');
$stmt->bind_param('s', $formdata);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}

Append 2 Mysql rows

I have a two step registration, one with vital data, like email username and password, and a second optional one with personal info, like bio, eye color, etc.. i have 2 exec files for these, the first ofc writes the data in the first part of the database, leaving like 30 columns of personal data blank. The second one does another row, but with the vital data empty now.. I would like to append, or join these two rows, so all the info is in one row..
Here is the 2nd one
$qry = "UPDATE `performers` SET `Bemutatkozas` = '$bemuatkozas', `Feldob` = '$feldob', `Lehangol` = '$lehangol', `Szorzet` = '$szorzet', `Jatekszerek` = '$jatek', `Kukkolas` = '$kukkolas', `Flort` ='$flort', `Szeretek` = '$szeretek', `Utalok` = '$utalok', `Fantaziak` = '$fantaziak', `Titkosvagyak` = '$titkos_vagyak, `Suly` = '$suly', `Magassag` = '$magassag', `Szemszin` = '$szemszin', `Hajszin` = '$hajszin', `Hajhossz` = '$hajhossz', `Mellboseg` ='$mellboseg', `Orarend` = '$orarend', `Beallitottsag` = '$szexualis_beallitottsag', `Pozicio` = '$pozicio', `Dohanyzas` = '$cigi', `Testekszer` = '$pc', `Tetovalas` ='$tetko', `Szilikon` ='$szilikon', `Fetish1` = '$pisiszex', `Fetish2` = '$kakiszex', `Fetish3` = '$domina', `Testekszerhely` = '$pchely', `Tetovalashely` = '$tetkohely', `Csillagjegy` = '$csillagjegy', `Parral` = '$par', `Virag` = '$virag' WHERE `Username` ='" . $_POST['username']. "'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: perf_register_success.php");
exit();
I'm not sure if $_POST works here. I have the form, then the exec of that form, which works, then this form, and this is the exec of that.. Anyway I always get "query failed" message, which is in the else statement of the 'if' i'm using. What am i doing wrong?
Thanks!
The correct syntax for UPDATE is as follows:
UPDATE table SET columnA=valueA, columnB=valueB WHERE condition=value
(documentation here)
Thus, your query should look like the following:
$qry = "UPDATE performers SET Bemutatkozas = $bemuatkozas, Feldob = $feldob, Lehangol = $lehangol [...] WHERE Username ='" . $_POST['username']. "'
You'll have to replace [...] with all your values (that's gonna take some time) but hopefully you get the pattern.
Other than that there are a number of things you should improve/change in your code but I'll just point you to jeroen answer in this question since he pretty much covers it all.
You want UPDATE instead of INSERT for your second query.
Apart from that you really need to fix that sql injection error, preferably by switching to PDO or mysqli in combination with prepared statements. The mysql_* functions are deprecated.
And whatever solution you take, you need to add proper error handling, suppressing errors is wrong, especially when you try to fix a problem but even in a production site, errors need to be logged, not ignored.

Categories