Code won't insert into database - php

I have the following code that should collect the filled values from a former page and insert them in a MySQLi database. This does not work and I only get a blank page as a result, without any messages. I can't figure out what I'm doing wrong.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "INSERT INTO project VALUES('','$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<h1>Projektet är skapat!</h1><br>
Tryck på knappen nedan för att ta dig till Dashboard.<br><br>
<a href='dashboardadmin.php'><button id='projectbutton'>Dashboard</button></a>";
}
else
{
echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
}
?>

Correct syntax of INSERT is:
INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
Please try entering column names before your values first. Also check your $_POST values, whether $_FILES['image'] is available and confirm your mysqli connection.
Edits:
Is the first value (empty one) your primary key? If so, can you omit that bit in your code and try again? (Assuming pid is integer and auto incrementing value.)
INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('$company_name','$description','$image','$image_type','$welcome_text',‌​'$thanks_message')
Somehow I don't think this would be Azure specific issue as per your comment.
Can you see any errors in logs etc? Also try echoing the query before you run it and check if you run it directly on your phpmyadmin etc to see if it'd work.
Please also try using echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
at if($r){..} else { //here } to see if you get an error.
Latest Update:
$q = "INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('".$company_name."','".$description."','".$image."','".$image_type."','".$welcome_text."','".$thanks_message."')";

Try this, because your primary key value is auto incremented.
$q = "INSERT INTO project VALUES('$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";

Related

INSERT INTO statement won't insert a specific value correctly?

I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.

sql query work only with small strings and not with big length strings

here's the php script tht gets the string and insert it in the db .
<?php
include 'connect.php';
$name = $_POST['name'];
$message = $_POST['message'];
$message = nl2br($message);
if(isset($name) && isset($message)){
$sql = "INSERT INTO messages VALUES('','".$name."', '".$message."')";
if($sqlrun = mysqli_query($connection , $sql)){
header('Location:../write.php');
}else{
echo "query doesnt work";
}
}
?>
what can be the reason it works only with small strings?
in the database the field is a text that contain 1000 bits maximum .
Why don't you check if there were any errors? any information is better than no information.
$sql = "INSERT INTO messages VALUES('','".$name."', '".$message."')";
if($sqlrun = mysqli_query($connection , $sql)){
header('Location:../write.php');
exit();
}else{
echo "query doesnt work: " . mysqli_error(); // jaaaj information!
}
I don't know why , but after i cheked the sql query time after time i realized that for the first argument in the values ( the '' which is dedicated for an auto-increment field) , i have to put NULL in there so that the query should be like this :
$sql = "INSERT INTO messages VALUES(NULL,'".$name."', '".$message."')";
again , i don't know exactly why now it works .
anyway thanks everyone !

How to POST a newly defined variable into SQL - beginners PHP

The sql column avatar_link isn't updating:
A form submits data and directs to the script (partial) below. The SQL columns: name, comment, email and story_id all insert fine. The image saves to the server with no problem (I didn't include that part of the script to keep things brief). $templink is a newly created variable that should represent the URL of a image uploaded. I'm redefining the variable as $avatar_link and using POST.
$tempLink = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
$page_path = $_POST['page_path'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $_POST['email'];
$storyid = $_POST['storyid'];
$avatar_link = $_POST['$tempLink'];
$con=mysqli_connect
("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'INSERT INTO comments (name, comment, email, storyid, avatar_link, entry_date)';
$sql .= 'VALUES("'.$name.'", "'.$comment.'", "'.$email.'", "'.$storyid.'", "'.$avatar_link.'", now())';
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
I marked the title of this 'beginners PHP' because this question seems very basic (and I can't still figure it out)...if that is not appropriate let me know and I will remove.
$_POST variables come from a submitted form. If you are simply defining a variable and passing it into a statement for insertion into a database, you could eliminate a few steps here, and just do this:
$avatar_link = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
Also, pay attention to #Marc B's comment here. You can learn about parameterizing mysqli statement all over the web, or here on Stack Overflow. What's really best, and what I'd recommend, is learning PDO.

Enter variable into sql table Problems

Ok I am having problems insert a variable into a sql table. Heres my code
if (isset ($_GET['comment']))
$commentEntered = $_GET['comment'];
else
$commentEntered = "refuse";
Above I get the variable
Then I try to pass it to the database with the code below
$sql = "insert into $DB_Table (comment) values('$commentEntered');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
My problem is, When I pass a single word it works, But when the text box where comment is received has any spaces in it, It will not insert?
i.e - The user enters Hello - This works
The user enters Hello World - This doesn't work
Any help would be much appreciated!
try
$sql = "INSERT INTO " . $table . " (comment) " .
"VALUES ('" . mysql_real_espace_string($commentEntered) . "')";
Also, dump the var $commentEntered before the "$sql = ..." line just to see what it outputs to the screen.
var_dump($commentEntered);
And another thing, try switching from GET request method to POST and grab the data from $_POST.
try to call:
mysql_query("COMMIT");
before closing the connection.

Why can't I INSERT INTO?

So this might be dumb, but I can't get anything to insert into a MySQL on a certain account, and I've been staring at this for two hours. I'm a newbie to PHP, so I could very well be doing something dumb. I attached a screen shot of the DB I am trying to INSERT INTO.
Here is what I'm talking about:
(imgur seems to be down for me)
Here's the code I have, and PhpMyAdmin told me GRANT ALL PRIVILEGES ON . TO ...
$fbFirstName = $me['first_name'];
$fbLastName = $me['last_name'];
$fbEmail = $me['email'];
mysql_real_escape_string($fbFirstName,$fbLastName,$fbEmail);
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
$userrowsreturned=mysql_num_rows($getuserresult);
if ($userrowsreturned=0)
{
echo '<br />user already exists, will update something here eventually<br />';
}
else {
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES ($uid,'1','0',$fbEmail,$fbFirstName,$fbLastName)");
if(!$sql) {
die("Nope");
} else {
echo "1 record added";
}
echo '<br />created user<br />';
}
Two things go wrong here. Escaping goes like:
$fbFirstName = mysql_real_escape_string($fbFirstName);
// for all variables
// or, just in one go:
$fbFirstName = mysql_real_escape_string($me['first_name']);
// and for integers, make sure they are actually integers (and prevent mayhem)
$some_id = (int)$me['some_id'];
$uid = (int)$uid;
And when inserting you must quote non-integer values:
$sql = mysql_query("INSERT INTO `newusers`
(`fbUID`,`callsAttempted`,`callsMade`,`fbEmail`,`fbFirstName`,`fbLastName`)
VALUES
('$uid',1,0,'$fbEmail','$fbFirstName',$fbLastName')");
(but you may quote integers as well - you never know if some external id is, or may become, alphanumeric.)
You have an error
if ($userrowsreturned=0)
should be (use double equals to test equivalence, single equals for assignment)
if ($userrowsreturned==0)
I also think you actually mean the following since you're checking if a user already exists
if ($userrowsreturned==1)
first of all you must change
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
to
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID='$uid'");
after that change your insert to:
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES
('$uid','1','0','$fbEmail','$fbFirstName',$fbLastName')");

Categories