Inserting into MySQL database - php

I am trying to insert data into MySQL database. For each of the data been inserted I want the username to be added so as to keep track of the user the insert that data.Here is my sample query below but the username is not inserting.
$username = $_SESSION['log']['username'];
$Query = "INSERT INTO core_modules
(username,courseID,title,credits)
VALUES ('$username',SELECT ID,title,credits FROM module
WHERE ID IN ('CS4150','CS4403','CS4407','CS4501','CS4504','CS4614'))";
mysql_query($Query);
echo $Query. '<br />';
This is what my database looks like and I need the username inserted into each record inserted.
How could I go about this please ?? Thanks in advance.

INSERT INTO core_modules (username,courseID,title,credits)
SELECT '$username', ID, title, credits
FROM module
WHERE ID IN ('CS4150','CS4403','CS4407','CS4501','CS4504','CS4614')

Related

Display the item selected by specific user in status page for that specific user

I would like to ask how to display the information based username? I mean when I login, it will lead me to select data page. My select data page has username, name and date. The name is the name of item in spinner, i put these item in spinner. For example, username which is john select item 1 in spinner and it will send to database. Then when go status page, it will only display the item selected by John only in John account. Same as other account, in their account only will display their own item selected.
Below is my select item php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
$date = $_POST['date'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name, date) VALUES
('$username','$name', '$date')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Selected Successfully';
}else{
echo 'Sorry, You Already Select this item';
}
//Closing the database
mysqli_close($con);
}
?>
View Status Php:
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM Selection";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"username"=>$row['username'],
"name"=>$row['name'],
"date"=>$row['date']
)
);
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I am using localhost and phpmyadmin.
Table structure for Selection is below:-
id - primary key Not Null
username NOT NULL,
name NOT NULL,
date NOT NULL,
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
As you haven't mention the Schema of Spinner and Selection table, assuming a simple case for you, the solution would be like instructed below..
When user logs in, capture it's username (usually store it in session till he/she logs out).
In your Status.php your query would be
Select * from Selection where username = '$YOUR_USER_NAME_FROM_SESSION_HERE';
That should be enough as per your requirement.
NOTE: Using variable directly in your query will result in exposure of SQL injection. To prevent Sql injection, refer this answer too.
when the user logged in set the session using $_SESSION["name"] = "$username";
right now session is set then you can access the session variable from anywhere in the view page you retrieve the session using
$user= $_SESSION["name"].
now you fetch the items from the database
like
$sql = "SELECT * FROM Selection where username='$user'";
try it

Stuck at this error: Incorrect integer value: '' for column '____' at row 1

When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.

PHP MySQL Inserting data in a database table using PHP script

Using the given below php script, I connect to database and insert data in it. But the data is not getting inserted in my database table. It is also not throwing any error. Where is my code wrong?
<?php
$host = '127.0.0.1';
$uname='root';
$pswd='';
$myDB='portal';
if($myConn = new mysqli($host,$uname,$pswd))
echo 'Connected to MySQL server successfully.</br>';
else
echo 'Unable to connect to server</br>';
$database = mysqli_select_db($myConn,$myDB);
if($database)
echo 'Connected to database...</br>';
else
echo 'Database not found!</br>';
$var1='string1';
$var2='string2';
$query= "INSERT INTO users VALUES ($var1,$var2)";
$result = mysqli_query($myConn,$query) or die(mysqli_error($myConn));
?>
You have to add single quotes around the values:
$query= "INSERT INTO users VALUES ('$var1','$var2')
Or better use prepared statements. See this for an example.
In your statement, you must define the names of the target tables in your database, that the values should be inserted into, like this:
$query= "INSERT INTO users (Name,Age) VALUES ('$name','$age')";
if users table have only two columns, or two plus an auto-incrementing id the query is:
INSERT INTO users VALUES ('$var1','$var2')
if there are more columns or a non primary id the query is:
INSERT INTO users (col1,col2) VALUES ('$var1','$var2')
You also miss a parameter in the connection instantiation:
$mysqli = new mysqli($host, $uname,$pswd, $myDB);

PHP inserting data from one table to another

<?php
$con=mysqli_connect("localhost","usr","pwd","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, Name, email FROM users WHERE status='ACTIVE'");
while($row = mysqli_fetch_array($result)){
// echo $row['Name']. " - ". $row['email'];
// echo "<br />";
$userid = $row['id'];
$username = $row['Name'];
$email = $row['email'];
mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
VALUES ($userid, $username, $email)");
}
mysqli_close($con);
?>
i have the above code i am trying to insert data from one table to another
The above code do not returning any error but it do not puts any data to second table "other_user"
There is an error in INSERT query - you have to enclose strings in quotes, like this:
"INSERT INTO other_user (user_id, username, email)
VALUES ($userid, '$username', '$email')"
A single query would be enough:
$result = mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
SELECT id, Name, email FROM users WHERE status='ACTIVE'");
No need for an agonizing slow row by row insert.
PS: The original error was leaving out quotes around your values.
You should use mysqli prepared statement to insert data to table. Now you don't use quotes in your query (probably that's why data is not inserted into second table) and even if you were, it would be still vulnerable to SQL Injection
I think you should carefully check the table design of your new table.
Check if the column names and types are what you expect.
Also user_id in your new table may be an autoincrement index and than if doesn't have to be inserted.

Row created in mysql with no error, but no data inserted

Very new at this. I submit my input form, no errors come up. When I go to check the entry into myphpadmin, a row was created, but all the fields are blank.
Not sure what is going on as my text code with only 4 entries works.
<?php
$subscribingcompany= $_POST["subscribingcompany"];
$biztype= $_POST["biztype"];
$sitename= $_POST["sitename"];
$siteadd1= $_POST["siteadd1"];
$city1= $_POST["city1"];
$zip1= $_POST["zip1"];
$state1= $_POST["state1"];
$country1= $_POST["country1"];
$biladd1= $_POST["biladd1"];
$city2= $_POST["city2"];
$zip2= $_POST["zip2"];
$state2= $_POST["state2"];
$country2= $_POST["country2"];
$fename= $_POST["fename"];
$lename= $_POST["lename"];
$email1= $_POST["email1"];
$phone1= $_POST["phone1"];
$foname= $_POST["foname"];
$loname= $_POST["loname"];
$email2= $_POST["email2"];
$phone2= $_POST["phone2"];
$effdate= $_POST["effdate"];
$camquantity= $_POST["camquantity"];
$currency= $_POST["currency"];
$quantity= $_POST["quantity"];
$database="greenguy_cbrsandbox";
$table="DesignPartner";
//Create connection and select database
$con= mysql_connect("example.com", "greenguy_ccb", "password88") or die(mysql_error());
echo "connected";
mysql_select_db("$database", $con) or die(mysql_error());
echo"database found";
//Insert into Table
$insert = "INSERT INTO $table
(id, subscribingcompany, biztype, sitename, siteadd1, city1, zip1, state1, country1, biladd1, city2, zip2, state2, country2, fename, lename, email1, phone1, foname, loname, email2, phone2, effdate, camquantity, currency, quantity)
VALUES
(DEFAULT,'$subscribingcompany','$biztype','$sitename','$siteadd1','$city1','$zip1','$state1','$country1','$biladd1','$city2','$zip2','$state2','$country2','$fename','$lename','$email1','$phone1','$foname','$loname','$email2','$phone2','$effdate','$camquantity','$currency','$quantity')";
$results =mysql_query($insert) or die(mysql_error());
echo"data inserted succesfully";
mysql_close($con);
?>
You Insert query is working properly as you have provided the auto increment functionality
row is getting created but rest of the values are not getting inserted please echo your query during execution .
use echo $insert to know what is getting inserted when query is executing.

Categories