Insert data into table at one time - php

This is my code
echo '<input type="submit" name="submit">';
I am getting the data from another table with this query
if($_POST['submit'])
{
$sql = mysql_query('SELECT q.username, q.firstanme,q.lastname FROM quizgroup q');
foreach($sql as $s)
{
$username = $s->username;
$firstname = $s->firstname;
$lastname = $s->lastname;
$sql = mysql_query('INSERT INTO user(username,firstname,lastname) VALUES('.$username.','.$first.','.$last.')');
}
}

Try this
insert into user (SELECT username, firstanme, lastname FROM quizgroup)
This statement will copy the data from quizgroup to user table
Dont use "values" keyword when copy the data
Look at this
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

Related

How to save result of a query in variable?

I'm trying to save result of a MYSQL query in variable. I know that results save as an array but I don't know how to assign result to variable.
I could echo result but I couldn't assign it to variable.
here is my code with error:
require('db.php');
$id =$_REQUEST['id'];
$name ="SELECT name FROM table2 WHERE id='".$id."'";
$name_result = $con->query($name);
while($row = $name_result->fetch_assoc()) {
$name=$row['name'];
}
$ins_query=" insert into table1 (`id`,`name`) values ('$id','$name')";
$stat=mysqli_query($con,$ins_query) or die(" error".mysql_error());
Id gets from user as html input field and will save in table1.
Name exists in table2 and I want to select it where id in table1 is equals with id in table2 then insert it in table1.
$name ="SELECT name FROM table2 WHERE id='$id'";
As you said that we can store variables as arrays
$array = array();
while($row = mysql_fetch_object($name))
{
$array[] = $row;
}
So after that $array[] will have the value that you want but if you want to have single variable instead of an array you can convert it by using equivalent. I hope that this one helps you.
Try this code:
require('db.php');
$id = $_REQUEST['id'];
//modification
$query = $this->db->prepare("SELECT name FROM table2 WHERE id=?");
$query->bind_param('s', $id);
$query->execute();
//assuming you are retrieving only 1 value
$result = $query->get_result->fetch_assoc();
if ($result) {
//value stored...use as you wish!
$name = $result["name"];
} //you can add your else
$this->db is your db connection

update specific row based on user selection using PDO via php issue

I am trying to update my sql table based off user input. So the user picks from a select list the column they want to update. Then they enter the data from the row and then what they want to update that with. so say the pick column teamname, the would then enter the team name they want to change via text box and then via another textbox enter the new name. Thats what Im trying to get to happen anyways.
I tried to copy and paste my code from where the user deletes data and modify it. I have tried a couple different things, the first thing I tried gave me this error:
UPDATE teams SET rockets = :value1 WHERE teamname = rockets
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rockets' in 'where clause'
My sql statement looked like this:
$sql = "UPDATE teams SET $selectData = :value1 WHERE $columnSelect = $selectData";
Then, I tried to do something like this:
entire code below, as stated above I have tried a couple different thigns with the $sql variable:
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$columnSelect = $_POST['selectColumn2'];
$selectData = $_POST['selectData'];
$updateData = $_POST['updateData'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "UPDATE teams SET :value1 = :value2 WHERE $columnSelect = :value1";
// use exec() because no results are returned
$stmt = $conn->prepare($sql);
$stmt->execute(array(':value1'=>$selectData, ':value2'=>$updateData));
if ($stmt->rowCount() > 0) {
echo 'Updated '.$stmt->rowCount().' rows';
} else {
echo 'No rows updated';
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
html
<form method='post' action='addData.php'>
Select a column name, then enter which data to update.
<br>
<br>
<label for='option2'>
<select name='selectColumn2'>
<option value='teamname' id='team2'>teamname</option>
<option value='city' id='city2'>city</option>
<option value='bestplayer' id='best2'>bestplayer</option>
<option value='yearformed' id='year2'>year</option>
<option value='website' id='website2'>website</option>
</select>
</label>
<label for='option2'>
select data to change: <input type='text' name='selectData'>
enter new data: <input type='text' name='updateData'>
</label>
<br><br>
<input type='submit' value='Submit New Entry'>
</form>
Basically what I what to do is take $columnSelect, find $selectData in that column and replace it with $updateData using the PDO method. What am I doing wrong?
This should work: UPDATE teams SET $columnSelect = :value1 WHERE $columnSelect = $selectData
Change your query like this,
$sql = "UPDATE teams SET `$selectData` = ':value1' WHERE `$columnSelect` = '$selectData'";
Add single quotes for string values while inserting or updating. And addd backtics for the table name or column names.
EDIT
$sql = "UPDATE teams SET `$columnSelect` = ':value1' WHERE `$columnSelect` = '$selectData'";

Input checkbox value that is created dynamically into MySQL if checked

I am pulling in questions from a questions table in MySQL and populating them in a form. This works fine and I am populating checkboxes as well that the value is populated with the QuestionID. The array is properly populating but I want to take the value of the checked checkboxes (which is my question ID) and insert that ID into a table, so that I have the questions that are selceted for use by their ID. Here is what I have so far:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name=chkQuestion align="left"/><p>' . $row['Question'] .'</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
if (isset($_POST['chkQuestion']))
{
//create the query for the score
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES ($QuestionID)";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Submitted!!</h1>';
}
}//End of IF 'submitted
You want to insert multiple records in one statement is what I'm understanding.
$sql2 = "INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(". implode('),(', $QuestionID) . ")";
This will join each index inside $QuestionID with ),(
If you were to echo $sql2 you would get
INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(1),(2),(3)
You can use a loop to get the questions that are checked.
for($i=0;$i<count($_POST["chkQuestion"]);$i++) {
"INSERT INTO tbl_QuestionSelected (QuestionID) VALUES('".$_POST["chkQuestion"][$i]."');
}
This way the MySQL statement has the actual values to insert into your table.
try to loop your ids and escape it!!
$ids_list = '';
foreach($_POST["chkQuestion"] as $id)
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($id);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
This will assign the value based on the array for the value and insert it into MySQL:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name="QuestionID[' . $row['QuestionID'] . ']">' .$row['Question']. '</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
$ids_list = '';
foreach($_POST["QuestionID"] as $key=>$value) {
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($value);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
}//End of IF 'submitted
}

Deleting Database Entries Not in Array

I have an array that grabs checkbox data and posts certain information into the database if the checkbox data isn't a copy of something already in the database. What I would like to know is how can I create a code that scans through the database and finds data that wasn't part of my checkbox data and delete it from the database.
Okay, for example let's say I have values 1,2,3,4 in my database, but in my checkboxes I only get back 1,2,4. I would like a code that scans my database and deletes that value(s) (in this case 3) from the database.
Here is my current code:
foreach($_POST['publish'] as $index => $val){
$matches = mysql_query("SELECT * FROM `$blog_table` WHERE `postID` = '$val");
if (mysql_num_rows($matches) > 0)
{
// do nothing
} else {
$query3 = "insert into `$blog_table`
(`postID`)values
('$val')";
mysql_query($query3);
}
}
Here would be the code I would use with escaped input
if (!empty($_POST['publish']))
{
$inserts = array();
$deletes = array();
foreach ($_POST['publish'] as $val)
{
$deletes[] = intval($val);
$inserts[] = '('.intval($val).')';
}
$delete = "DELETE FROM `".$blog_table."` WHERE postID NOT IN (".implode(',',$deletes).");";
$insert = "INSERT INTO `".$blog_table."` (`postID`) VALUES ".implode(',',$inserts)."";
}
you should use query like this:
delete from table where id NOT in (3)
in php like:
$query = "DELETE FROM `$blog_table` WHERE `postID` NOT IN (" . implode(',', $array) . ")";
For the MySQL query, you can use NOT IN:
DELETE FROM tablename
WHERE col1 NOT IN (1, 2, 4)

how to insert an hidden field value along side with a checkbox in to the database

i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}

Categories