Enter variable into sql table Problems - php

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.

Related

Code won't insert into database

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')";

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 !

PHP and SQL one page insert into database

I have written a PHP page with a form on the submit button I set the action to the PHP form page.
<form id="form1" method="post" action="../control_lbs/lbs_trace.php">
The INSERT INTO is basic sql load information to the database.
The problem i have every time I open the page it sends blank information to the rows. Is there away I can prevent this from happening?
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req,
lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES
('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]'
,'$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
The above is my PHP action code
This is the new code and full code I use
if ($con = mysql_connect($host, $username, $password)) {
if ( !empty($_POST["send"])) {
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES ('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]','$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
On refresh or page entry it still gives me blank info on Database
You need to use isset() to see if the $_POST variables are set. I've use $_POST in the example below, I suggest you give the submitbutton a name (like example) and use isset($_POST['example']):
if( isset($_POST) ){
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES(
'".$_POST['lbs_msisdn']."',
'".$_POST['lbs_req_by']."',
'".$_POST['lbs_date_req']."',
'".$_POST['lbs_reason']."',
'".$_POST['lbs_station']."',
'".$_POST['lbs_cas']."',
'".$_POST['lbs_traced_by']."'
)";
echo $sql; // echo it to see if it has any values
// print_r($_POST); // in case the query is still empty, uncomment this. It will show you the values in the POST array
}

Using a form to update data in MySQL

Having trouble getting my form to UPDATE records in my database even after searching the web and viewing the other answers on stack-overflow.
Here is my current NON functioning code:
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
session_start();
$tablename = $_SESSION['MM_Username'];
$amount=$_POST['amount'];
$UpdateQuery = "UPDATE '" . $tablename . "' SET stock = '" . $amount . "' WHERE status = 1";
mysql_query($UpdateQuery);
}
The table i want to update has the same name as the SESSION variable MM_Username. I have a form with a textbox named amount and a Submit button that when clicked, should trigger the above code. If you need to know anything else let me know. Thanks in advance!
You're using the wrong quotes around your table name. Also, your query is open to SQL injection. Consider using PDO and bind parameters.
$UpdateQuery = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1',
$tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
Have MySQL tell you what the problem is. Change the last line of your code to this:
if (!mysql_query($UpdateQuery)) {
echo mysql_error();
}
Print out if you are having your tablename in your session variable.
print $_SESSION['MM_Username'];
Also print out the $UpdateQuery and see how the mysql query is formed. Copy that query & try running it manually in mysql to see if the query is ok.
ADVISE: I see that you have used $_POST. This is fine, but I advise you to use $_REQUEST. This var in PHP has all $_POST & $_GET content. Sometimes one forgets to change the $_POST to $_GET or vice versa & ends up wasting his time, debuggin.
if (!mysql_query($UpdateQuery)) {
echo mysql_error()
}

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