I have three columns that I want to insert data into using php. the code will be run three times.
I want if run the code the first time to insert only on column1 while leaving other columns empty.
If run the second time to insert into only column2 while leaving other column empty
and so on. I have tried the code below but cannot get it to work. it only inserts into the column1
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT * FROM rec');
$result->execute(array());
while ($row = $result->fetch())
{
//$id = $row['id'];
$column1 = $row['column1'];
$column2 = $row['column2'];
$column3 = $row['column3'];
}
if ($column1 ==''){
echo 'empty';
$statement = $db->prepare('INSERT INTO rec(column1)
values(:column1)');
$statement->execute(array(':column1' =>'$column1'));
} elseif ($column2 ==''){
echo 'empty2';
$statement = $db->prepare('INSERT INTO rec (column2)
values(:column2)');
$statement->execute(array(':column2' =>'$column2'));
} elseif ($column3==''){
echo 'empty3';
$statement = $db->prepare('INSERT INTO rec(column3)
values(:column3)');
$statement->execute(array(':column3' =>'$column3'));
}
Firstly it is not a proper way of designing database.
Secondly, use if statements only rather than nested if-else statements and it will work!
Your if-else is such that the correct data is not getting inserted properly . Use the following code which will solve your purpose in your way . However , the way you are following is not correct . Either you follow the conventional way to create a database and inserting values into it or use dynamic fields for a table and insert it another way .
if ($column1 ==''){
echo 'empty';
}
else{
$statement = $db->prepare('INSERT INTO rec(column1)
values(:column1)');
$statement->execute(array(':column1' =>'$column1'));
}
if ($column2 ==''){
echo 'empty2';
}
else{
$statement = $db->prepare('INSERT INTO rec (column2)
values(:column2)');
$statement->execute(array(':column2' =>'$column2'));
}
if ($column3==''){
echo 'empty3';
}
else{
$statement = $db->prepare('INSERT INTO rec(column3)
values(:column3)');
$statement->execute(array(':column3' =>'$column3'));
}
Related
I have an auto incrementing ID called deviceID in one of my fields. I was wanting to pass this to a session in php to use later on and was planning on using scope_identity() as I understand that this is the best way to get the current Primary key ID. However anytime I have attempted to use it I have had a error message saying that it is an undefined function. Here is my code so without the scope_identity():
<?php
session_start();
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["screenWidth"] = $screenWidth;
$_SESSION["screenHeight"] = $screenHeight;
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["HandUsed"] = $HandUsed;
$_SESSION["phoneName"] = $phoneType;
echo 'hello';
$sql = "
INSERT INTO DeviceInfo (DeviceID, screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')
SELECT SCOPE_IDENTITY() as DeviceID
";
if (sqlsrv_query($conn, $sql)) {
echo ($sql);
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>
You need to fix some issues in your code:
The INSERT statement is wrong - you have five columns, but only four values in this statement. I assume, that DeviceID is an identity column, so remove this column from the column list.
Use parameteres in your statement. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Use SET NOCOUNT ON as first line in your statement to prevent SQL Server from passing the count of rows affected as part of the result set.
SCOPE_IDENTITY() is used correctly and it should return the expected ID. Of course, depending on the requirements, you may use IDENT_CURRENT().
The following example (based on the code in the question) is a working solution:
<?php
session_start();
include 'db.php';
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['phoneName'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$params = array($screenWidth, $phoneType, $screenHeight, $HandUsed);
$sql = "
SET NOCOUNT ON
INSERT INTO DeviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES (?, ?, ?, ?)
SELECT SCOPE_IDENTITY() AS DeviceID
";
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error: " . $sql . ": " . print_r(sqlsrv_errors());
exit;
}
echo "New record has been added successfully !";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DeviceID"];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
?>
$allgames = file_get_contents("https://steamspy.com/api.php?request=all");
$decodeall = json_decode($allgames, true);
foreach($decodeall as $game) {
$sql = "INSERT INTO games (name)
VALUES ('{$game['name']}')";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
When i do this only the first row will be added. How do i insert multiple rows?
Just get rid of that multi query thing. Use a prepared statement instead
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach($decodeall as $game) {
$name = $game['name'];
$stmt->execute();
}
echo "New records created successfully";
Note that your current code with multi_query won't work as intended anyway, even with that silly typo fixed. You will have the result of only first query, having no idea what happened to all others.
You are overwriting the query each time. Try setting sql to blank then appending it each time in the loop.
Try this:
$sql = array();
foreach($decodeall as $game) {
$sql[] = "INSERT INTO games (name) VALUES ('{$game['name']}')";
}
$sqlInserts = implode(';', $sql);
if ($conn->multi_query($sqlInserts) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You don't need to perform the query multiple times like that, you can do it all in a single query without multi_query(). You can perform many INSERTs with a single query, like this
// Initialize the query-variable
$sql = "INSERT INTO games (name) VALUES";
// Loop through results and add to the query
foreach ($decodeall as $game) {
$sql .= " ('".$game['name']."'),";
}
// Remove the last comma with rtrim
$sql = rtrim($sql, ',');
// Perform the query
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will generate a query resembling
INSERT INTO games (name) VALUES ('One'), ('two'), ('Three')
which will insert the values One, Two and Three into separate rows.
This query will break if your $game['name'] variables contain an apostrophy ', so at the very least you should use $mysqli::real_escape_string(), although a prepared statement takes care of that and prevents SQL injection (so I recommend you go for that instead). See How can I prevent SQL injection in PHP?
Using a prepared statement - the better solution
The preferred method of executing a query is by using a prepared statement.
Fetch all the columns using array_column() and loop the array while calling the execute method until finished.
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach (array_column($decode, "name") as $name) {
$stmt->execute();
}
I have a web application in which students are divided into "batches".
I am trying to insert student for particular batch and the batch will be chosen by user by select option. After that student is added to the particular batch, he/she will be added to stdhold table. However, it is only inserting for the first selected value of select option.
<?php
function specialCOn() {
$connew = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connew,'mcqs');
return($connew);
}
if (isset($_POST['add']))
{
$namestd=$_POST['std_name'];
$batchstd=$_POST['batch'];
$FNAME=$_POST['f_name'];
$query3 = "INSERT INTO `$batchstd` VALUES('','$namestd','$FNAME')";
$rsq3 = mysqli_query(specialCOn(),$query3);
mysqli_close(specialCOn());
$queryrollno = "select rollno from `$batchstd` order by rollno desc";
$rsqrollno = mysqli_query(specialCOn(),$querrollno);
$getrollno = mysqli_fetch_array($rsqrollno);
$rollnoto = $getrollno[0];
echo "<script>alert('$batchstd')</script>";
echo "<script>alert('$rollnoto')</script>";
mysqli_close(specialCOn());
//Problem is here
$querystdhold = "INSERT INTO stdhold VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd')";
$rsqhold = mysqli_query(specialCOn(),$querystdhold);
mysqli_close(specialCOn());
if ($rsq3&&$rsqhold)
{
echo "<script> alert('Student Added.');
window.location.assign('addstudent.php');
</script>";
//header('Location:addstudent.php');
}
else
{
echo "<script> alert('You Havenot added Student.');
window.location.assign('addstudent.php');</script>";
}
}
?>
Try use this :
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO ? (col1,col2,col3) VALUES('',?,?)");
$stmt->bind_param('sss', $_POST['batch'], $_POST['std_name'], $_POST['f_name']);
$stmt->execute();
For the detail example you need to read the #Amber Answer how to create secured prepared statement.
Hope this'll help you.
Try specifying the column names in your insert query:
INSERT INTO stdhold (col1, col2, col3, col4) VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd');
For reference see the MySQL Insert documentation.
I have been given a task to convert the hardcoded fields into dynamic fields.I have changed it partially to dynamic
Let me explain you the situation ,
We have a lot of databases and each database has a table by name Surveys
By using the DESCRIBE statement we will retrieve the fields in the Surveys table regardless of the database .
I need to know the way where we can loop again and again till all the fields in the survey table appears.
In the below code I have left the for loop blank .
Please let me know the changes that neeeds to be done to get this working
I would really appreciate any kind of help
function insertIntoUserUploadFileds() {
$describe="DESCRIBE surveys";
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
$inUse="0";
$type="";
//for(){
if($field=='type'){
$type="N";
}elseif(($field=='fname') || ($field=='lname') || ($field=='phone')){
$inUse="1";
$type="T";
}elseif($field=='email'){
$inUse="1";
$type="E";
}
//$sql .= "('".$field."', '".$inUse."', '0', '
$result1 = mysql_query ($describe);
$result = mysql_query ($sql);
//}
}
$result1 = mysql_query ('DESCRIBE surveys');
//here is how you retieve all field and check
while($row = mysql_fetch_array($result1)) {
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
//here you can do if else to check the column name
if($row['field']=='type')
{
$type="N";
}
else if(($row['field']=='fname') || ($row['field']=='lname') || ($row['type']=='phone'))
{
$inUse="1";
$type="T";
}
else ($row['field']=='email')
{
$inUse="1"
$type="E";
}
//build your query
$sql .= "('".$field."', '".$inUse."', '0', '......)
//execute your complete query
$result = mysql_query ($sql);
}//end of while
Instead of using DESCRIBE, if you are trying to retrieve the default type of a particular column you might look into this. It describes how to break down the information from a particular table. Codex
I'm creating a class and I have a function with which I want to insert some data into an table from some inputs. It works if I check the table but I keep getting the error "number of arguments in prepare doesn't match the no of arg in bind_result". Also I don't know if my method is correct ..
private function insertData($foldName,$foldClass,$foldLink) {
$sql = "INSERT INTO folders (folder_name,folder_class,folder_link) VALUES ('$foldName','$foldClass','$foldLink')";
if($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($foldName,$foldClass,$foldLink);
$stmt->close();
$error = false;
$message['error'] = false;
$message['message'] = "Data Successfuly Inserted";
return json_encode($message);
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "Data Failed To Insert";
return json_encode($message);
}
}
You don't need bind_result at all as you are inserting data and not selecting any.
But you should use the core features of your prepared statement. That is: safely passing the variables to the statement object instead of inserting their "raw" values into the SQL string:
$sql = "INSERT INTO folders (folder_name,folder_class,folder_link) VALUES (?,?,?)";
$stmt = $this->connect->prepare($sql);
$stmt->bind_param("sss", $foldName, $foldClass, $foldLink);
$stmt->execute();
(I have not tested it.)
Look at the first example on this manual page: http://php.net/manual/en/mysqli-stmt.bind-param.php
If you are emptying the table's data as a whole, use the truncate query:
TRUNCATE TABLE `table_name`
This would reset the auto_increment to 1, but if you don't want to empty the whole table you can alter it instead:
ALTER TABLE `table_name` auto_increment = 1