ERROR on this Php file:
<?php // Insert Comments into Database that user provides
//Get values of fields entered
$comment = $_POST['addComment'];
$pID4 = filter_var( $_POST['pID'], FILTER_SANITIZE_STRING );
$cID = $_POST['prefix'] . $_POST['code'];
require_once('inc/dbc1.php');
$pdo4 = new PDO('mysql:host=###;dbname=####', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
/* Error on this line --> */ $sth4 = $pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES('$comment',?,?);');
$sth4->execute(array($comment, $pID4, $cID));
?>
ERROR: syntax error, unexpected T_VARIABLE
From what I can see, the info field is required (i.e. cannot be null) but I can't see where you are setting the $info variable to pass into the prepared statement.
Try restarting mysql in debug mode, which should allow you to get the exact query being run - you can then see if it's a MySQL problem or a PHP problem.
You're not outputting your pID into your form, because of mal-formed string output:
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }
echo "</select>
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
<input type='hidden' name='pID' value='<?php echo $pID4; ?>'>
^^^^^^^^^^^^^^^^^^^^^ here
</form>";
At the point I've indicated, you're still within the double-quoted string for the 'echo' command, so that PHP never gets executed, as it's within the string. What you'll end up with is an HTML tag that looks like
...<input type="hidden' name='pID' value='<?php echo 1234;?>'>...
in the browser, which is not what you want.
You really need to either "break out" of PHP mode, or use HEREDOCs. Either will let you output multi-line text chunks without having to jump through hoops with mixing quoting styles, and also let any decent syntax-highlighting editor catch errors such as this.
$pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES('.$comment.',?,?);');
that's wrong. use this:
$pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES(?,?,?);');
Related
Im trying to add text to a database with a text entry, heres the part of the text entry of index.php:
<form action="steamauth/senddb.php" method="get">
<input type="text" name="username" placeholder="John Doe">
<input type="text" name="steamid" placeholder="12939124953">
<input type="text" name="server" placeholder="VanityRP | DarkRP"><br><br>
<input type="submit" class='btn btn-success' style='margin: 2px 3px;'>
</form>
Now heres the steamauth/senddb.php code:
$value1 = $_POST['username'];
$value2 = $_POST['steamid'];
$value3 = $_POST['server'];
$sql = "INSERT INTO StaffTeam (username, steamid, server) VALUES('".$value1."', '".$value2."', '".$value3."')";
if ($conn->query($sql) === TRUE) {
echo "Admin added succesfully, redirecting in 3 seconds...";
header( "refresh:3;url=http://vanityrp.site.nfoservers.com/index.php" );
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
So, now, the problem is, im getting empty records on the database, how can i fix that
There are 2 things wrong here.
First, you're using a GET method in your form, but then using POST arrays.
Both need to match. POST/POST and not GET/POST.
Then you're outputting before header with echo on top of headers.
How to fix "Headers already sent" error in PHP
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
If you are trying to pass data that MySQL will complain about, such as John's Bar & Grill (apostrophes), then you will need to escape your data; something you should be doing anyway.
I.e.:
$var = mysqli_real_escape_string($conn, $_POST['var']);
Your column types and lengths should also be correct and able to accomodate the data.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure you are successfully connected to your database with mysqli_.
Different MySQL APIs do not intermix. (sidenote).
Good day people,
some days ago, I started learning php and now I'm at the point where I intend to teach myself database queries with mysql.
My current code, however, won't process anything.
It's supposed to take text input from the index.html, pass it to a.php and have the a.php look for the (name /) input string in a database (phone book), then output the matching row(s) in a table.
It consists of two parts; the index.html which is just the following:
<form action="a.php">
<input type="text" name="q">
<input type="submit">
</form>
and the a.php which is supposed to process the inputted data:
<?php
echo $_GET['q'];
$such = $_GET['q'];
$mysqliu = new mysqli("HOST", "User", "Password", "Database");
$sql="Select * from LIST where name like '%$such%'";
$result = mysqli_query($mysqliu,$sql);
if($result = $mysqliu->query($sql)) {
echo "<table><tr><th>Kennummer</th><th>Name</th><th>Strasse</th><th>PLZ</th><th>Telefon</th></tr>";
while($row = $result->fetch_array() ) {
echo "<tr>";
echo "<td>" , "$row[0]" , "</td>";
echo "<td>" , "$row[1]" , "</td>";
echo "<td>" , "$row[2]" , "</td>";
echo "<td>" , "$row[3]" , "</td>";
echo "<td>" , "$row[4]" , "</td>";
echo "</tr>";
}
}
$result->close();
echo "</table>";
else {
echo"Nope"
}
$mysqliu->close();
?>
I tried outcommenting as much as possible to see where it breaks and it seems that as soon as I want to do something to "q" (the query from index.html), it breaks.
The above code doesn't contain the SQL connection data but that's present in my code.
The issue is not related to the PHP server or anything server-side so I'm sure I'm doing something wrong.
I can echo the variable q in a.php so it's passed over but whatever I do after that, nothing happens and I get a blank page.
Can you experts help me please?
Solved: It was the ; missing right at the end.
Thanks to everyone for their input.
Regards~
Try to add a method in the form tag like GET or POST. Set a default value for the q field. Also set a name for the type submit and dump the whole $_GET or $_POST array in the php file.
I won't give you the exact answer, I'll let you figure it out...
use error_reporting
Check your IF-ELSE statement, does it look correct??
Note:
You don't have a method attribute in your <form>
What if a user just typed-in their browser, a.php? You should be validating the page so user can't just access this page
Is your table really LIST? Be case sensitive about it.
Your query is still prone to SQL injections. You should be using mysqli_real_escape_string() extension of PHP, or better use mysqli_* prepared statement.
Your form should look like this:
<form action="a.php" method="GET">
And sanitize the values of your passed on data:
$such = mysqli_real_escape_string($mysqliu,$_GET["q"]);
If you are curious with prepared statement, you can try this:
$such = "%".$_GET["q"]."%";
$mysqliu = new mysqli("HOST", "User", "Password", "Database"); /* REPLACE NECESSARY DATA */
if($stmt = $mysqliu->prepare("SELECT kennummer,name,strasse,plz,telefon FROM LIST WHERE name LIKE ?")){ /* REPLACE NECESSARY COLUMN NAME */
$stmt->bind_param("s",$such); /* BIND PARAMETER TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($kennummer,$name,$strasse,$plz,$telefon); /* BIND THE RESULT TO VARIABLE */
?>
<table>
<tr>
<th>Kennummer</th>
<th>Name</th>
<th>Strasse</th>
<th>PLZ</th>
<th>Telefon</th>
</tr>
<?php
while($stmt->fetch()){ /* LOOP THE RESULT */
?>
<tr>
<td><?php echo $kennummer; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $strasse; ?></td>
<td><?php echo $plz; ?></td>
<td><?php echo $telefon; ?></td>
</tr>
<?php
}
?>
</table>
<?php
$stmt->close();
}
Solved: It was the ; missing right at the end. Thanks to everyone for their input.
First, you need to enable error reporting in the page using error_reporting(-1);. As you are getting error but that is not getting display because error reporting is OFF.
Second, your code welcomes to SQL injections So It is better to learn first that how you can avoid SQL injections after that approach for queries in database.
Third, You need to check MySQLi extension is installed or not on your PHP. Use var_dump(function_exists('mysqli_connect')); and then check the output.
Fourth, $mysqli->fetch_array(); returns weird results sometimes that is because of old PHP version so that can be a reason of error, please check once with that.
Fifth, I believe there is an error with your if else statement. else statement should start after } of if statement .
I can edit my answer once you please show the exact error in your question from error log meanwhile you can check with these.
I got the error: unknown column in field list, while I know for sure I haven't made any typos and the columns exist.
Anyone know what I'm overlooking?
<?php
//create_cat.php
include '../includes/connection.php';
$cat_name = mysql_real_escape_string($_POST['cat_name']);
$cat_description = mysql_real_escape_string($_POST['cat_description']);
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo "<form method='post' action=''>
Category name: <input type='text' name='cat_name' id='cat_name'/>
Category description: <textarea name='cat_description' id='cat_description' /></textarea>
<input type='submit' value='Add category' />
</form>";
}
else
{
//the form has been posted, so save it
$sql = 'INSERT INTO categories(cat_name, cat_description) VALUES ($cat_name, $cat_description)';
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
else
{
echo 'New category successfully added.';
}
}
?>
Try this:
$sql = "INSERT INTO categories(cat_name, cat_description) VALUES ('$cat_name', '$cat_description')";
Update:
You used ' to start a string. When doing this its not possible to use variables in the text, they will just be leaved as plain text. But when using " the variables will be evaluated.
The problem is your SQL query. You used single quotation marks, which is for a literal string. Your variables will not be parsed in. You need to use double quotation marks. Not only that, but for strings, you need to put single quotation marks around them when putting them into queries.
$sql = "INSERT INTO categories(cat_name, cat_description) VALUES ('$cat_name', '$cat_description')";
You should also try not to use mysql_* anymore. It's been depreciated (meaning it will be removed from PHP soon). Try looking at MySQLi (very similar to MySQL) or PDO instead.
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.
HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.