PHP email glitch - php

This is a school assignment. I don't know all of the fine details of PHP variables and such, but! If I hardcode the id then it sends just like it should. If not, it doesn't at all. Suggestions?
if ((!empty($_subject)) && (!empty($_text))) {
$_dbc = mysqli_connect('localhost', 'user', 'password', 'db') or die ('Error Connecting to MySQL server.');
$_id = $_GET['id'];
$_query = "SELECT * FROM midterm WHERE id = '$_id'";
$_result = mysqli_query($_dbc, $_query) or die ('Error Querying Database.');
while($_row = mysqli_fetch_array($_result)) {
$_to = $_row['email'];
$_firstName = $_row['firstName'];
$_msg = "Dear $_firstName, /n $_text";
mail($_to, $_subject, $_msg, 'From:' . $_from);
echo 'Mail sent to: ' . $_firstName . ' at ' . $_to . '<br />';
}

Addressing $_GET/$_POST problems with a NULL $_GET['id']
<form name="example" action="http://example.com" method="POST"></form>
OR
<form name="example" action="http://example.com" method="GET"></form>
If variables are POSTed from a form, they will be sent through the server and you can access them on the submitted page with $_POST['key']. If variables are sent with GET, they will be appended to the URL in a query string and accessible on the page with $_GET['key'].
When you use the variable $_GET['id'] it is looking in the URL's query string for the key id. If your URL looked like http://example.com/sript.php?id=123 then $_GET['id'] would return 123 not NULL. This can either be accomplished by visiting a specific URL (like shown above) or arriving on the page through a form like below:
<form name="example" action="http://example.com/script.php" method="GET">
<input type="text" name="id" />
<input type="submit" value="Try Me" />
</form>
This form, when submitted, will send the $_GET['id'] variable to script.php using GET.
Addressing other issues with mail not sending
Can you add the following lines of code before your while loop and let me know what they say? This will let me know if your MySQL query is working.
echo "Rows returned: ".mysqli_num_rows($_result)."<br />";
// this line only works on PHP > 5.3.0
echo "Result dump:<br /><pre>".mysqli_fetch_all($_result)."</pre>";
Since mysqli_num_rows() returned 0, that means that your SQL query SELECT * FROM midterm WHERE id = '7' is not returning any results. I can't help any more without looking at the database structure. Double check your code (and compare it to code that works) to try to see what is going wrong. Make sure that there is a row in the table midterm that has an id = 7.

Related

Specifying ID in Mysqli query in php

I'm working on a CMS site, I've got blog posts that I store in a database. I can create, edit and delete them. There's an issue though when I want to edit them.
I can't specify the WHERE clause in the update query to match the id of the blog post I'm trying to edit!
Suppose I've got a blog post with an id of '5'.
If I write this code for it, it works exactly the way it should.
$sqledit = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
But I don't want to edit just blog post #5, I want to edit the blog post that I'm updating. It seems to me this should work,
WHERE id= $_POST[id]";
... but it doesn't.
That just throws me an undefined id error. But it shouldn't because I can delete blog posts the exact same way with this particular code:
$sqldel = "DELETE FROM `paginas` WHERE id= $_POST[id]";
This does allow me to.
The code below is on the blog page, the edit query is in its own edit.php page
if (isset($_POST['edit'])) // if pressed, execute
{
echo
'<br><br> <div class="blogscript">
<form action="edit.php" method="post">Edit your stuff<br>
<input type="text" placeholder='. $pagetitle . ' ><br><br>
<textarea id="message2" name="message"><p>' . $message . '</p></textarea><br>
<input type="submit" name="editsubmit" value="Confirm" />
<input type="hidden" name="id" value="' . $id . '">. </form></div>';
}
I look forward to any tips I should try out.
EDIT:
This is my edit.php page
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "cmsbase";
$MySQLi_CON = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLi_CON->connect_errno)
{
die("ERROR : -> ".$MySQLi_CON->connect_error);
}
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $MySQLi_CON->error;
}
$MySQLi_CON->close(); //close connection
echo "<script>alert('Edited');location.href='index.php';</script>";
?>
EDIT: This is what the var_dump contains
In order for values to be present in $_POST, you need to have some element (e.g. <input>, <select>, <textarea>) inside your form with a name attribute set to the $_POST key you want.
You can add a hidden input to your form for id.
<input type='hidden' name='id' value='" . $id . "'>
Assuming you are getting the $message variable shown in that form code by selecting from your database, you should be able to get the id from there as well, or potentially from your $_GET if that is how you determine which post is being displayed.
(While this is not actually an answer, what I want to say does not fit in the comments)
Your line
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
Is horrific. This is the stuff of nightmares. Lets say that POSTed data in a form, is posted from a script from some robot somewhere, because I'm pretty sure you don't prevent XSRF in your code.
What if that script chose to post:
$_POST ==> array => message = "mwahahaha";
=> id = "1; DROP TABLE paginas;"
And you may think "how would they know my table name?" ,but that's easily found from other nefarious id inserts or other hacks on your code from other entry points which give a SELECT result, and many tables have common names such as "users" / "orders" / "baskets" / "touch-me" etc. (Ok well maybe not touch-me, but you get the idea).
Mysqli_real_escape_string() Could be used but thats only escaping quote marks and special characters, it does not mitigate SQL injection and compromise.
So, what should you do?
In this instance I want to draw your attention to PHP type juggling. Unlike many other languages, PHP has implied data types rather than specific data tyes, so a data type of "1.06" can be string and juggled to being a float as well.
Your id parameter in your MySQL is very probably a numeric integer value, so how can you be sure that the value of $_POST['id'] is also in integer rather than a SQL Instruction?
$id = (int)$_POST['id'];
This forces the value to be an integer, so
$id = (int)"1; DROP TABLE paginas;";
Is actually processed as $id = 1. Therefore saving you lots of compromised tables, spam rows and other nefarious rubbish all over your website, your database and your reputation.
Please take the following concept on board:
NEVER EVER TRUST ANY USER SUBMITTED CODE.
EVER

In PHP MySQL query returns EVERY row. In MySQL Workbench, it works correctly

I have a very simple PHP form:
<form action="listtenants.php" method="post">
Search for Tenant: <input name="term" type="text" value="" />
<input name="Submit" type="submit" />
</form>
At first I thought, the data was posting incorrectly; but after viewing the headers with LiveHTTP headers, it turns out it is posted correctly.
Here is my PHP script. Like I said, the query works correctly in MySQL workbench; however in the PHP script, every row is returned. Does anyone know why this could be? Even echoing the posted variable returns the expected string. Not sure what gives here.
<html>
<body>
<?php
$connect = mysql_connect("host","user","pass");
mysql_select_db("db", $connect);
$term = $_GET['term'];
$query = "SELECT itemid, first, last FROM tenants where CONCAT(first, last) LIKE '%$term%'";
$getUserid = mysql_query($query);
//$i = 0;
$records = mysql_num_rows($getUserid);
while($row_sections = mysql_fetch_array($getUserid))
{
echo "$row_sections[0] $row_sections[1] $row_sections[2]";
?>
<br><br>
<?php
}
?>
</body>
</html>
This is a terrible query and highly dangerous. BUT.. ..your issue is simple.
Your form submits via _POST, and your looking for variables using _GET.
$term = $_GET['term'];
will always be empty, so your query matches on '%%' - ie: everything!
Change it to:
$term = $_POST['term'];
..then go read about MySQL injections and follow the links in the comments to your post.

button to call php to delete mysql row via ID

Hi I have a html form button called delete. Next to the button is an input area. The logged in user will enter a number corresponding to the ID then press delete. It should delete the row corresponding to that ID.
For some reason it doesn't work.
This is my html form:
<h3 class="block-head">Delete Job</h3>
<form action="deletejob.php" method="post" class="basic-grey">
<label>Please Enter Job ID</label><input type="text" name="idnum" id="id"/><br>
<input type="submit" name="delete" value="delete"/>
</form>
This is my php code:
mysql_connect("********", "root", "******")
or die("Connection Failed");
mysql_select_db("jobslist")or die("Connection Failed");
$idnum = $_POST['id'];
$query = "delete from jobs_list where idnum = '".$id."'";
if(mysql_query($query)){ echo "deleted";}
else{ echo "fail";}
I know about switching to mysqli and that...I just want to see if this method works first.
thanks.
the name of your input is idnum yet you are looking in the $_POST array for id and in your query using the variable $id when you declare $idnum in the line previous.
$idnum = intval($_POST['idnum']);
$query = "delete from jobs_list where idnum = '".$idnum."'";
PHP receive the data via $_POST as an array of input elements with the key as the NAME of the input field, so you have to change this line:
$idnum = $_POST['idnum'];
You can also change the input name and don't change the php code:
<input type="text" name="id" id="id"/>
It's a typical mistake, don't worry too much about that :P
You should change the POST value.. and then try
$idnum = $_POST['idnum'];
Change the HTML, update the input type id to:
id="idnum"
then, update the PHP query while fetching the post value to:
$idnum = $_POST['idnum'];
It should work.

Why is my Select Statement not working properly?

I am trying to select rows in my table sql. I have done this many times and for this instant it wouldn't work.
Displaying the variable $id, displays correct value, which means it receives a correct value from $_POST however after using it on Select Statement and using mysql_fetch_array, nothing displays.
my code
$id=$_POST['idsend'];
$edit = mysql_query("SELECT * FROM students WHERE id= '$id'") or die(mysql_error());
$fetch=mysql_fetch_array($edit);
echo 'ID= '.$id; ---------> This one displays properly
echo 'ID= '.$fetch['id']; --------> displays nothing
Please help me find out what's wrong. Hehe thanks in advance.
It would be safer to use PDO, to prevent SQL Injection (I made a PDO example of your query):
// it's better to put the following lines into a configuration file!
$host = "enter hostname here";
$dbname = "enter dbname here";
$username = "enter db username here";
$password = "enter db password here";
// setup a PDO connection (needs some error handling)
$db_handle = new PDO("mysql:host=$host;dbname=$dbname;", $username, $password);
// prepare and execute query
$q_handle = $db_handle->prepare("select * from students where id = ?");
$id = $_POST["idsend"];
$q_handle->bindParam(1, $id);
$q_handle->execute();
// get stuff from array
$arr = $q_handle->fetch(PDO::FETCH_ASSOC);
echo $arr["id"];
First of all, you shouldn't use mysql_* functions anymore.
You code fails because mysql_fetch_array() only returns a resource, you need to loop over it to get the actual result.
while ( $row = mysql_fetch_array( $edit ) ) {
printf( 'ID: %s', $row['id'] );
}
Okay, I have found out what's wrong. I apologize for disturbing everyone. I have realized what's wrong in my code and you won't find it on the code I posted in my question.
Carelessness again is the cause for all these. :) hehe
This is where the error is coming from
<form action="" method="post">
<input type="hidden" name="idsend" value="' . $row['id'] . '"/>
I have assigned a variable on a value with extra spaces/character? So the code must look like this.
<input type="hidden" name="idsend" value="'.$row['id'].'"/>
It must be assigned properly to work smoothly with the select statement.
I guess echo-ing the values isn't enough to see if there's something wrong.
Sorry for the trouble.

POST doesn't work fine

Well I have a problem with my code:
if ($_POST) {
//send confirmation email (or insert into database, etc...)
if(isset($_POST['del'])) {
$Link = $_POST['del_link'];
$query = "UPDATE comentarios SET del = '1' WHERE id = '".$Link."'";
mysql_query($query) or die ('Error: ' . mysql_error());
//header('Location: http://google.es'); //For debug
}
}
echo '<form name="del" method="post">
<input type="hidden" name="del_link" value="'.$rowComen['id'].'" />
Delete
</form>';
But when I press the link the web refreshes and that's all...
I had tried with: header('Location: http://google.es'); But I don't redirect to google...
And I don't know if the problem is in the post or in the query...
if(isset($_POST['del'])) {
You dont seem to have del form field. so the code inside this if statement is never executed. i think you are trying to check for del_link. so make it as if(isset($_POST['del_link'])) {
Have you checked in your browser if it contains the right value? The form as it is will contain the exact value '.$rowComen['id'].', unless a part of the PHP code is missing and the form is actually inside a string..
[edit]
I see. The form's name is 'del', but that name is never sent. Make the name of your submit button 'del', or add another hidden element. Easier still: Just check for the existence of del_link instead of del:
if(isset($_POST['del_link'])) {
$Link = $_POST['del_link'];

Categories