Data not inserting into database to a table - php

I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help

You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php

Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.

Related

Combine INSERT INTO SELECT, with DELETE at the same time

I have a button
<button onClick=sAve('save','."$id."']."')>SAVE</button>
Once I click it, I want to use AJAX to pass the parameters to the PHP page to perform the following task to MYSQL:
switch... case "Save":
$sql1 = "INSERT INTO permanent_table (id, user, email)
SELECT id, user, email
FROM temp_table WHERE id='".$_GET['id']."'";
$sql2 = "DELETE FROM temp_table WHERE id='".$_GET['id']."'";
Whereby permanent_table having same structure as temp_table. I tried to run both queries just like that but it is not working, so I guess that is not the right way.
In my case, my question is:
What is the real pro way to use PHP/sql to perform this task?
Is there any way I can simplify/combine it to a single query?
I think this is you want
<button onClick="$.post('/php file name/', {'save','."$id."'}, function(data){});">SAVE</button><br/>
Then you could run some query's in the PHP file.
$sql = $conn->prepare("INSERT INTO `permanent_table` (`id`, `user`, `email`) VALUES(?, ?, ?)";
$sql->bind_param("sss", $_GET['id'], "", "");
$sql->execute();
$sql = $conn->prepare("DELETE FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
$sql = $conn->prepare("SELECT `id`, `user`, `email` FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
//select last so that you can grab the results
Run them on your way (PDO or MYSQL)
I know a lot about query's so feel free to ask something to me!

PHP not performing INSERT to MySQL on form post

I am trying to make a product spec form add to a table called ProductSpecs on post, however despite the same synatx working fine for SELECT does not work for INSERT. The permissions to the MySQL account used allow full read/write, and I am able to insert into the database via console input using the same request.
Any ideas will be most appreicative.
$sql = " INSERT INTO ProductSpecs (SpecID, Code, ProductName, Barcode, ProductDescription, SKU, CYear, HeaderStyle, Certification, InnerQTY, OuterQTY, PackagingDescription, Comments) VALUES (NULL, '$Code', '$ProductName', '$Barcode', '$ProductDescription', '$SKU', '$CYear', '$HeaderStyle', '$Certification', '$InnerQTY', '$OuterQTY', '$PackagingDescription', '$Comments')";
$result = $conn->query($sql);
Thanks
You don't have to regard SpecID in your query. It should be auto increment not null value, so don't regard it and it will work fine.
You want to try and write your code with prepared statements and you can choose PDO or MySQLI. Here is an example how to do it with PDO. Also I would look at this link it might help you. http://prash.me/php-pdo-and-prepared-statements/ along with these videos https://www.youtube.com/watch?v=bvxid3DoLjE.
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "test123";
$db_name = "test_db";
$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt= $dbh->prepare("INSERT INTO tests(name1, name2, name3, name4,name5,name6, name7, name8, name9, name10) Values (?,?,?,?,?,?,?,?,?,?)");
$stmt->bindParam(1, $_POST["name1"]);
$stmt->bindParam(2, $_POST["name2"]);
$stmt->bindParam(3, $_POST["name3"]);
$stmt->bindParam(4, $_POST["name4"]);
$stmt->bindParam(5, $_POST["name5"]);
$stmt->bindParam(6, $_POST["name6"]);
$stmt->bindParam(7, $_POST["name7"]);
$stmt->bindParam(8, $_POST["name8"]);
$stmt->bindParam(9, $_POST["name9"]);
$stmt->bindParam(10, $_POST["name10"]);
$stmt->execute();
?>
Try putting columns names inside ``
$sql = "INSERT INTO ProductSpecs (`SpecID`, `Code`, `ProductName`, `Barcode`, `ProductDescription`, `SKU`, `CYear`, `HeaderStyle`, `Certification`, `InnerQTY`, `OuterQTY`, `PackagingDescription`, `Comments`) VALUES (NULL, '$Code', '$ProductName', '$Barcode', '$ProductDescription', '$SKU', '$CYear', '$HeaderStyle', '$Certification', '$InnerQTY', '$OuterQTY', '$PackagingDescription', '$Comments');";
$result = $conn->query($sql);
if fails echo last error message and comment.
the SepcID may have been set as not null which may cause the problem.
Try not referencing your ID column?
$sql = " INSERT INTO ProductSpecs (Code, ProductName, Barcode, ProductDescription, SKU, CYear, HeaderStyle, Certification, InnerQTY, OuterQTY, PackagingDescription, Comments) VALUES ('$Code', '$ProductName', '$Barcode', '$ProductDescription', '$SKU', '$CYear', '$HeaderStyle', '$Certification', '$InnerQTY', '$OuterQTY', '$PackagingDescription', '$Comments')";
$result = $conn->query($sql)

Can't get mysql_insert_id() method to grab value I need

I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

PHP/SQL can't insert

So I'm doing a register page for teams. So the user who creates a team will be inserted into a database table called alcs_teams. That's not the problem. Then I'd like to insert them into another table called alcs_member_teams. That keeps track of the members on each team.
So I do an insert query into the alcs_teams which works fine. Then I try to select the team id from the data that was just inserted a few lines below. Does this work? I can't get it to work, it just puts 0 in that field in the database.
$member = mysql_query("Select * from members where id=$_SESSION[tid]");
$member = mysql_fetch_array($member);
mysql_query("INSERT into alcs_team (teamid, name, leader, email) VALUES('', $_POST[name]', '$member[name]','$member[email]')");
$teamid = ("Select * from alcs_team where leader=$member[name]");
$row = mysql_fetch_array($teamid);
mysql_query("INSERT into alcs_member_teams (id, alcs_teamid, alcs_memberid, member_name) VALUES ('', '".$row[teamid]."' , '".$member[id]."', '".$member[name]."')");
You should look into using parametrized queries whenever possible
Example:
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$params = array($name, $email);
$sql = 'INSERT INTO CustomerTable (Name, Email) VALUES (?, ?)';
$stmt = sqlsrv_query($conn, $tsql, $params);
This prevents SQL Injection, which can cause a lot of trouble on your site.

Categories