Only numbers get inserted in sql - php

So i have this form
<form>Tag name:
<input type='text' name='tagname' />
<input type='submit' value='Add' />
<input type='hidden' name='id' value='$id' />
</form>
<hr />
it runs this script
if ($tagname)
{
mysql_query("INSERT INTO tags (id, tag) VALUES ($id, $tagname)");
?>
<script type="text/javascript">
alert("Tag added.");
history.back();
</script>
<?php
}
If i insert numbers in form it gets added to sql database nicely,but if it consist of alphabetical characters i get the alert but nothing is inserted in database.
I checked phpmyadmin if the structure is wrong(text/varchar/int...) tried most of them but it is the same.

You need single quotes to enclose strings within SQL queries:
mysql_query("INSERT INTO tags (id, tag) VALUES ('$id', '$tagname')");
And I'm conjecturing you also forgot to apply mysql_real_escape_string beforehand.

mysql_query("INSERT INTO tags (id, tag) VALUES ($id, '$tagname')");
Very common mistake. Think about escaping, or better - parametrizing queries. Concatenating an SQL query is an awful approach (so is putting in a small piece of code, together, HTML, PHP, SQL and JavaScript)

You need quotes around $id (unless it's a number) and $tagname in your mysql query.
As a side note, this is vulnerable to SQL injection.

I see a couple of issues with your code, first setting the value for the id input field:
<input type="hidden" name="id" value="<?php echo $id; ?>" />
And then, in the SQL you should use quotes:
mysql_query("INSERT INTO tags (id, tag) VALUES ($id, '$tagname')");

In so far as I can tell based on your code, and depending on how you're escaping, if you've no ajax to fetch the id you're running either of:
INSERT INTO tags (id, tag) VALUES (0, $tag)
INSERT INTO tags (id, tag) VALUES ('', $tag)
You should really be running:
INSERT INTO tags (tag) VALUES ('$tag')

Related

MYSQL Only numbers can be inserted to table

I have MySQL table called cashreg and it has only one row called also cashreg and is set to VARCHAR 64 and utf8_general_ci. The problem is that while using this form :
<td>
<input placeholder="<?php echo SETTINGS_NEWCASHIER; ?>" class="form-control floating-label" name="newCashregInput" id="newCashreg" /></br>
<input style="width: 100%;" class="btn btn-success waves-effect waves-light" type="submit" name="newCashreg" id="newCashreg" align="right" value="PridÄ—ti kasos aparatÄ…"></input>
</td>
and
if(isset($_POST['newCashreg'])) {
mysql_query("INSERT INTO ".$table['cashreg']." VALUES (".$_POST['newCashregInput'].")");
}
the data from this form can be added to table if value is only made from numbers for example "984133" and for example "851fff", "gsdagsd", "fsdfas521" can't be added
you need to specify the column name in your SQL query for inserting a record. see https://www.w3schools.com/sql/sql_insert.asp
I will suggest you look into PDO. Your code is not safe.
But the answer to your question is qoutes. After concatenating the SQL statement it's wrong.
So the correct string should be INSERT INTO cashreg VALUES ('value')
You can insert number without a problem but if when you try to insert an alphanumeric string you need to quote it.
More info https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
<?php if(isset($_POST['newCashreg'])) {
mysql_query("INSERT INTO $table['cashreg']."VALUES('".$_POST['newCashregInput']."')");
}
Your syntax is wrong. It should be:
INSERT into tablename (columnx, columny, etc) VALUES ('valX', 'valY', 'etc')
Stop using the ancient mysql lib. It has been removed from PHP. Please instead use PDO. And prepared statements, your current code is vulnerable to an SQL injection attack.
https://phpdelusions.net/pdo

Concatenation of multiple user entries and submission into a single MySQL database entry

I am referencing to a question here: Can I concatenate multiple MySQL rows into one field?
In this question multiple rows of a column are listed and separated by a "," using the GROUP_CONCAT function. I want to achieve something in reverse by concatenating multiple user inputs into a single database entry. Something like this:
<form action="server.php" method="POST">
<div>
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<button type="submit" name="submit">submit</button>
</div>
</form>
and php:
<?php
if (isset($_POST['submit'])) {
$value1 = mysqli_real_escape_string($conn, $_POST['value1']);
$value2 = mysqli_real_escape_string($conn, $_POST['value2']);
$value3 = mysqli_real_escape_string($conn, $_POST['value3']);
$sql = "INSERT INTO database (col1)
VALUES GROUP_CONCAT('$value1', '$value2', '$value3');";
mysqli_query($conn, $sql);
header("Location: ../web_page/client_database_page.php?add_client=success");
}
?>
I know some of you will say that it would not be good practice to do this and I should have an individual column for each user input, however there is a reason for not doing it this way. The user inputs are added based on the number of variables from another database. In this database a user can insert additional user inputs from the website, but it would not automatically add a column to the input database. So a single column row should be able to contain all the user inputs and than later be separated for interpretation when called from the database.
Anybody have any ideas?
How about grouping your input values as an array then using implode() function in PHP before you insert into DB, like:
<form action="server.php" method="POST">
<div>
<input type="text" name="values[]">
<input type="text" name="values[]">
<input type="text" name="values[]">
<button type="submit" name="submit">submit</button>
</div>
</form>
Then, in PHP:
if (isset($_POST['submit'])) {
$values = $_POST['values'];
$escaped_values = array_map([$conn, 'mysqli_real_escape_string'], $values);
$concat_values = implode(",", $escaped_values);
$sql = "INSERT INTO database (col1) VALUES ('$concat_values');";
mysqli_query($conn, $sql);
header("Location: ../web_page/client_database_page.php?add_client=success");
}
Here, I used comma , as separator on each values. Just change it to your preference.
EDIT:
Another solution would be to use JSON for this so you can easily access the data when retrieved. Depending on your MySQL version, you can use the JSON data type for the col1 column/field.
ALTER TABLE `table_name` CHANGE COLUMN `col1` `col1` JSON;
Then modify the code to:
$json = json_encode($_POST['values']);
$sql = "INSERT INTO database (col1) VALUES ('$json');";
And then later when you retrieve the data you can do something like:
$values = json_decode($row['col1'], true);
Which you can then iterate to echo multiple <input> tags with values taken from the db.
You can simply concat values using PHP. No need to use GROUP_CONCAT for this.
Try code like below:
$sql = "INSERT INTO database (col1) VALUES ('$value1 $value2 $value3');";
Note: Values can be separated by comma , or any other separator instead of space.

Submitting Comments using PHP MySQL debug

Just wondering if anyone can point out where I'm going wrong with the code below. I'm trying to gather the text from the form and UPDATE a field within the database with the text.
I have tested the SQL statement alone and it is updating the column correctly, but seems to be an issue with the PHP syntax as when i click on the submit button, it only insets '1' into the columns.
PHP:
$SubmitComments = isset($_POST['SubmitComments']);
$AddComment = isset($_POST['AddComment']);
if ($SubmitComments){
mysql_query ("UPDATE `table` SET `column` = '$AddComment' WHERE `column` = '$.....'") or die(mysql_error());
echo 'Comment added';
}
HTML:
<tr>
<td>Add Comment</td>
<td align="center"><form name="form1" method="POST" action=""><input name="AddComment" type="text" id="AddComment" autocomplete="off" placeholder="Add comments..." size="45px"><br />
<input type="submit" name="SubmitComments" id="SubmitComments" value="Submit"></form></td>
</tr>
Right, from the top. isset returns a bool, so $SubmitComments would only equal true or false, it will never equal the POST variable (Same with $AddComment). Consider instead:
if(isset($_POST['SubmitComments'])&&isset($_POST['AddComment']))
{
$SubmitComments = $_POST['SubmitComments'];
$AddComment = $_POST['AddComment'];
//Rest of Code
}
Second, table and column names do not need single quotes around them. And finally, as addressed in the comments, think about using MySQLi instead as if your script does eventually work, one malformed comment will erase your entire database.
Example:
If their comment is even just butts';-- It will make the SQL:
UPDATE table SET column = 'butts';--' WHERE column = '$.....'
Which is the equivalent of:
UPDATE table SET column = 'butts';
Making all of your comments just the word "butts", and that's just a humorously childish attack, compared to stealing usernames/passwords, trashing the database etc

Pass multiple variable through single checkbox

I am not sure the best way to do this or if it's even possible. Basically I have a checkbox that looks like this:
php
foreach($clients as $client){
echo'
<input type="checkbox" name="client_data[]" value="'.$class_id.'">
'.$client['first_name'].' ('.$client['nickname'].') '.$client['last_name'].'
<br />';
} // foreach($client
HTML looks like this
<form method="post" action="">
<input type="checkbox" value="?" name="client_data[]">
Dwayne (The Rock) Johnson<br>
<input type="checkbox" value="?" name="client_data[]">
Steve (Puddin) Robinson<br>
<input type="submit" value="Add" name="exist_to_class">
</form>
When the form is submitted I want to insert the
$first_name, $nickname, $lastname
into the db with a query that looks like this:
mysql_query("INSERT INTO `clients` (`user_id`, `first_name`, `last_name`, `nickname` `class_id`)
VALUES ('$user_id', '$first_name, '$last_name', '$nickname', '$class_id')");
Is this possible or am I even close on how I am attempting to set this up? I have not had much luck so far.
My db table looks like this:
I need to be able to enter the client multiple time with different class_id's.
What is the best way to accomplish this?
Here is the code that call the function to insert data into db:
if (isset($_POST['exist_to_class'])){
if (empty($_POST['client_data']) === true){
$errors [] = 'You much select a client to be added to the class.';
} else {
if (isset($_POST['client_data']) && !empty($_POST['client_data']));
list($first_name, $nickname, $last_name) = explode('|', $_POST['client_data']);
exist_client_to_class($class_id);
header('Location: view_class.php?class_id='.$class_id.' ');
}
} //isset
And here is my query:
function exist_client_to_class($class_id, $user_id){
$class_id = (int)$class_id;
$user_id = (int)$user_id;
mysql_query("INSERT INTO `clients` (`user_id`, `first_name`, `last_name`, `nickname` `class_id`)
VALUES ('$user_id', '$first_name, '$last_name', '$nickname', '$class_id')");
}
What am I doing wrong?
You can't pass more than one variable through a single checkbox. Marc B is right, in that if this is a database-backed application then the right way to do it would be to have the checkbox send the ID for the person who's selected, and use the ID to look up whatever information you need about them.
If you're not using a database, a quick-and-dirty way to do this would be to put the information about the person into an array and then run it through serialize() to turn it into a string and use that as the value attribute. On the other end you can run it through unseialize() to get back the array with the values you wanted.
Remember that if you do this, you need to either escape your sql query or (very strongly preferred) use a prepared query.
okay, you may path string in value as Asad suggested and than split it on the server, like this
foreach($clients as $client){
echo'
<input type="checkbox" name="client_data" value="'.$class_id.'|'.$client['first_name'].'|'.$client['nickname'].'|'.$client['last_name'].'">
'.$client['first_name'].' ('.$client['nickname'].') '.$client['last_name'].'
<br />';
} // foreach($client
and on the server have something like
list($class_id, $first_name, $nickname, $last_name) = explode('|', $_POST['client_data'])
mysql_query("INSERT INTO `clients` (`user_id`, `first_name`, `last_name`, `nickname` `class_id`)
VALUES ('$user_id', '$first_name, '$last_name', '$nickname', '$class_id')");
I am not sure where from $class_id variable in template and $user_id in the model, so you have to figure it out, also drawback here is that if in some variable will be placed delimiter | data will be split wrong. To avoid it you may use hidden inputs associated somehow with the main checkbox (javascript, logic or whaterver will play best in your case)
UPD: oh yea you may serialize/unserialize data as array http://us3.php.net/serialize as octern suggestion

mysql_query in a while loop

I'm trying to execute
I have an html form in a page of this sort :
Name: <input type="text" id="namebox" value="" name="fields[]" /> <br />
Position: <input type="text" id="positionbox" value="" name="fields[]" /> <br />
<input type="hidden" name="createcard">
<input type="submit" value="Create">
.. and 3 other fields. I'm passing these 5 form fields by POST to a file process.php which has the following function to insert the array elements into a mysql DB.
if(isset($_POST['createcard'])){
$this->procCreateCardtheme1();
..
..
function procCreateCardtheme1(){
global $session;
$cardData = $_POST['fields'];
$username=$session->username;
$sno=1;
echo count($cardData);
while($sno < count($cardData))
{
$v=$cardData[$sno];
echo $v;
mysql_query("INSERT INTO carddata VALUES ('$username', $sno, '$v', 1)");
$sno++;
}
Now, the echo statement above returns the expected output, that is the five or so fields. But the mysql_query only executes once. It just stores the first entry in the DB, and nothing else. Even re-submitting the form does nothing at all. It's just the one entry that is stored in the DB.
Any ideas?
Do you have a unique constraint on username in the carddata table? This will cause the second insert to fail.
To debug this you should add some error checking to your program:
mysql_query("INSERT INTO carddata VALUES ('$username', $sno, '$v', 1)")
or trigger_error(mysql_error());
You might also need to use mysql_real_escape_string to avoid syntax errors or possible SQL injection vulnerabilities if the string data can contain quotes.
Single Loop iteration issue occurs when you have issue with variable for query ($query)
and Result Object ($result).
Try different name for variable inside the WHILE Loop or debug the variable inside the loop.

Categories