mysql_query in a while loop - php

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.

Related

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.

Handling Nulls from form input to SQL

So,
I am trying to create dynamic SQL queries where we assume:
If the _GET or _POST doesn't have a variable set we call it NOT SET
If the _GET or _POST is set but the value is empty then we call it EMPTY
If the _GET or _POST is set but the value is not empty then we call it NON-EMPTY
Now we can easily store the EMPTY and NON-EMPTY variables in MySQL as they are (because we know the intention of the end user since the variables have been set)
OUR Mapping so far:
EMPTY & NON-EMPTY = whatever the value is...
(for date column in MySQL since it doesn't allow empty we put in 0000-00-00 00:00:00. We use this logic for both the INSERTS and UPDATES
NOT-SET in PHP = NULL in database? (since we don't know anything about the value)
Now this works perfectly for situations where data doesn't already exist for example INSERT statements, but what about UPDATE STATEMENTS?
What if the record already has a value?
I am thinking of using NOT SET variable as to be ignored in UPDATE statements?
So if, lets say POST["name"] is not set on INSERT, then we still insert it as a null
INSERT INTO person (name) VALUES (POST["name"]);
but, if it is an UPDATE statement, we ignore it completely.
UPDATE person
isNull(POST["name"]) ? SET name = POST["null"]
My dilemma is what do we do for INSERTS and UPDATES when these variables are NOT SET?
<html>
<body>
<form method="post">
<label for="field_1">Field 1</label>
<br />
<input type="text" name="field_1">
<br />
<br />
<label for="field_1">Field 2</label>
<br />
<input type="text" name="field_2">
<br />
<br />
<label for="field_1">Field 3</label>
<br />
<input type="text" name="field_3">
<br />
<br />
<input type="submit" name="submit" value="submit">
</form>
<?php
// BASIC IDEA:
// (This example assumes all incoming post values are strings,
// if you have, for example, integers, you'd need to remove the
// single quotes around the values in the SQL statement)
// Loop through POST array
// foreach _POST variable as key => value
foreach($_POST as $k => $v) {
// if not null, blank, or "submit"
if(!is_null($v)&& $v != ''&& $v != 'submit') {
if(!isset($strSQL)) {
// If this is the first value, start off the sql string w/ UPDATE
$strSQL = "UPDATE your_table " ."SET " .$k ." = '" .$v ."'";
} else {
// For subsequent values, include a comma and space before new value
$strSQL = $strSQL ."', SET " .$k ." = '" .$v ."'";
}
}
}
// Finish off SQL Command, if one was ever started
if(isset($strSQL)){
$strSQL = $strSQL ." WHERE some_field meets_your_conditions;";
// Run SQL Command (echo just used for example)
echo $strSQL;
}
?>
</body>
</html>
In case of no set:
Insert:
INSERT INTO person (name) VALUES (NULL);
Update:
Don't call update if no set as the value can either be :
1) Null : If null no need to update it
2) Not Null: If not null, then you will be loosing values if you assign it null.
PS: This is my suggestion as per understanding of the requirement, but
it may differ as per actual requirements.

What MySQLi data type should be used for values from <option>

I am trying to insert a value into a MySQLi row using a select box, as seen below.
<select name="post_game"><option value="minecraft">Minecraft</option></select>
But I am faced with the error:
Undefined index: post_game
Is this because I should be using a different data type as oppose to using Varchar? I am also inserting values into other MySQLi rows using < input > instead of < select >, and they seem to go through just fine, which is why I believe it may have to do with the data type, and not my code.
But here is my code anyway:
<select name="post_game"><option value="minecraft">Minecraft</option></select>
$game=$_POST['post_game'];
$query = mysqli_query($con,"INSERT INTO servers (game) VALUES ('$game')");
Varchar will work just fine. If that is your entire code that you posted it won't work since there is not post request being made, in order to do that you need a form element
<form method="post">
<select name="post_game">
<option value="minecraft">Minecraft</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
<?php
if (isset($_POST["submit"]) && isset($_POST["post_game"]))
{
$game = mysqli_real_escape_string($con,$_POST["post_game"]);
$query = mysqli_query($con,"INSERT INTO servers (game) VALUES ('$game')");
}
?>
And also think about security as well. Bind your params, I'm on my phone so I wpnt get into that. This should be enough to get you going though

Splitting variables from $_POST

I wanted to split my variables from a form, and enter them into a Mysql Database one by one.
My table 4 fields would be: UserID, Status, HowLate, PassFail
In this example below the UserID would be 75 and 76, but can be any # from the user id in the future. I am confused on how I would be able to insert these dynamic variables into the database since I don't know what they will be each time. The only static pattern I have is when I loop through foreach ( $_POST as $key => $value ) any help
$results = print_r($_POST, true);
sample data from form
75=PRESENT
d75=on time
cc75=passed
76=LATE
d76=10 minutes
cc76=failed
I would want to write a query like:
insert into attendance (UserID, Status, HowLate, PassFail) values (76, 'Late', '10 minutes', 'failed')
also think of this as students in a class, so there is 20 records coming back at once
I'm guessing the reason you're doing this is because you're unaware that you can send multidimensional arrays in HTML forms. I suggest an approach such as.
<input name="users[1][userid]" />
<input name="users[1][status]" />
<input name="users[1][howlate]" />
<input name="users[1][passfail]" />
<input name="users[2][userid]" />
<input name="users[2][status]" />
<input name="users[2][howlate]" />
<input name="users[2][passfail]" />
Then in php you can access them in the following manner.
foreach( $_POST['users'] as $key => $user )
{
$userID = $user['userid']; // same for the other fields.
}
Assign your variables (if you are not using PDO, which you should to avoid SQL injection) for example:
$userId = $_POST['userId']; // assuming that is what your field id is from the html form
$status = $_POST['status'];
etc.
Then insert into the database table:
insert into attendance (UserID, Status, HowLate, PassFail) values ($userId, '$status' etc.

Only numbers get inserted in sql

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

Categories