Me again. I'm really new to PHP though have been really trying hard to practice, so terms are a little iffy right now.
My issue at the moment is my CMS can't seem to submit data to a MySQL table. Here is my function:
function newEntry() {
$query = mysql_query("INSERT INTO entries VALUES(null,'name','description','content')") or die(mysql_error());
}
Here is my form for submitting content:
<form action="doNewEntry.php" method="post">
<textarea name="entTitle" id="entTitle">Entry Title</textarea><br>
<textarea name="entDesc" id="entDesc">Input Description Here</textarea><br>
<textarea name="entCont" id="entCont">Type and format content here! What you see, is what you get.</textarea><br>
<script>
CKEDITOR.replace( 'entCont' );
</script>
<table><td colspan="2"><input type="submit" name="submit" /></td></table>
</form>
And here is the in between file to make the post:
<?php
include('includes/functions.php');
if(isset($_POST['submit'])) {
if(isset($_POST['entTitle'])) {
newEntry($_POST['entTitle'],$_POST['entDesc'],$_POST['entCont']);
header("Location: entries.php");
} else {
echo "Please fill out all fields!";
include('newEntry.php');
}
}
?>
I'm incredibly new to this, so it's no doubt a very simple fix. Maybe just missed something but I really cannot figure it out. ADD problems. :(
function newEntry()
You have passed the parameters to this function but dint received in definition.
function newEntry($title, $description ,$content){
//your code here
}
Need to reform this query
$query = mysql_query("INSERT INTO entries VALUES(null,'name','description','content')") or die(mysql_error());
You need to pass your variables in your function so add arguments to your function, otherwise it won't work, also your variable should be prepended by $ in your query, so change the function as follow
function newEntry($name, $description, $content)
{
$query = mysql_query("INSERT INTO entries VALUES(null,'$name','$description','$content')") or die(mysql_error());
}
As side note i would say that your code is higly vulnerable to mysql injections. I would rather switch to either PDO or mysqli and use prepared statments to avoid any risk.
Related
So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.
I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: login.php');
die();
}
if ($_POST['submit']) {
$title = strip_tags($_POST['title']);
$subtitle = strip_tags($_POST['subtitle']);
$content = strip_tags($_POST['content']);
mysqli_query($dbCon, $userREQ3);
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.
Index
<form action="logout.php">
<input type="submit" value="Log me out!">
</form>
<form method="post" action="admin.php">
Title: <input type="text" name="title"/><br>
Subtitle: <input type="text" name="subtitle"/><br>
<br>
<br>
Content: <textarea name="content"></textarea>
<input type="submit" value="Write Post"/>
</form>
</body>
</html>
Your code is failing for two reasons.
Your conditional statement is looking for a named element called "submit"
You're trying to execute before the statement. Place your query (mysqli_query())"below" the values and do mysqli_query($dbCon, $userREQ3) or die(mysqli_error($dbCon));
Sidenote: Change if ($_POST['submit']) { to if (isset($_POST['submit'])) { it's better.
and <input type="submit" value="Write Post"/>
to <input type="submit" name="submit" value="Write Post"/>
SQL injection:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
Also, you have variables in the body of your code, which may throw undefined variable x on initial page load.
Use a ternary operator for this
http://php.net/manual/en/language.operators.comparison.php
Use this for all your inputs/variables
As stated (in comments below): Make sure that you have connected to your database and using a mysqli method and not another API.
https://secure.php.net/mysqlinfo.api.choosing
Different MySQL APIs do not intermix with each other. Use the same MySQL API from connection to query.
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: Error reporting should only be done in staging, and never production.
Successful query or not:
To see if the query was indeed successful, or failed, check for errors and use affected_rows.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.affected-rows.php
PHP Not Inserting Content in mySQL Database: Text, Images, Anything
If you were trying to use images, then a valid enctype is required to be included in the form tags.
Depending on how/what you wanted to insert for the images, than that could be a factor.
If you're wanting to insert the image as a path is one thing, but using it "as an image", say a BLOB then that has limitations in size; use LONGBLOB and you must escape that data before going in the database.
Consult:
https://dev.mysql.com/doc/refman/5.0/en/blob.html
http://php.net/manual/en/features.file-upload.post-method.php
Try to generate the query first, then execute it...
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title', '$subtitle','$content')";
mysqli_query($dbCon, $userREQ3);
I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.
I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5
I'm having a big issue here, I'm trying to upload some data to a database, and I really don't have a clue why it isn't getting uploaded.
This one here is my HTML form to send data to the php. (This one here should have no problem at all)
<form method="post" action="uploadinfo.php">
<div style="width:542px;height:129px;margin-left:45px;margin-top:102px">
<textarea name="stufftoupload" placeholder="Write your stuff here" rows="8" cols="65"></textarea>
</div>
<div style="width:95px;height:29px;margin-left:489px;margin-top:22px">
<input type="image" src="myimg.png">
</div>
</form>
And this one here is my PHP to upload to the database, this is where the problem should be, but I have no clue what it is. I've tried several solutions, but nothing is working.
<?php
session_start();
$db = mysql_connect("host","db","pass");
if(!$db) die("Error");
mysql_select_db("table",$db);
$email = $_SESSION['email'];
$stuff = $_POST['stuff'];
if (!$stuff)
{
echo "<script type='text/javascript'>window.alert('Fill all the blanks.')</script>";
$url = 'upload.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
else
{
$url = 'success.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
mysql_query('SET NAMES utf8');
$sql = "SELECT * FROM table WHERE email = '$email'";
$result = mysqli_query($db,$sql);
mysqli_fetch_all($result,MYSQLI_ASSOC);
$sql = "INSERT INTO table SET stuff = '$stuff'" or die(mysql_error());
$result = mysql_query($sql);
?>
So this is about it, I'm almost positive it's something within this code, but it could be some bad session managing, though I'm not totally sure about it.
Anyway, thanks in advance for the help. It'll be totally appreciated.
$db is connecting to the database using the mysql method, but you are querying based on the mysqli methods. There are 2 things you need to do here to have an idea of what is going on. Firstly, change all your mysql_ calls to mysqli_ calls, and add some error reporting (so for example adding or die (mysqli_error($db); to the end of every line where you query) should point you in the right direction.
Your first glaring problem here is that you conneced to the DB using mysql_connect, but are then trying to query that connection using mysqli. Use one, not both.
Also, your SQL Query should read INSERT INTO table (stuff) VALUES ($stuff) rather than INSERT INTO table SET stuff = '$stuff'
There are a few problems here so I'll start with what I see now.
This line:
$db = mysql_connect("host","db","pass");
is what connects to your database and I'm assuming that "host" doesn't point to anything. Depending on where that is running, normally Localhost is used. You would also need to make sure the password is correct.
As suggested, use mysqli.
Your insert needs to be something like:
INSERT INTO table VALUES ({$stuff});
Not sure what you want from that form but your session variables will have to match the input names you use on the form.
$stuff = $_POST['stufftoupload'];
I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.
You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";
You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";
For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.