MySQL & PHP Insert Query Failing - php

I know there isn't enough validation in here just going through some testing. $result always returns empty? Is my query bad? I'm new to PHP and concatenating variables into strings is not something I have grasped full. Going with the OOP form since I'm pretty familiar with it and the concepts.
Also, I know this code is terribly sloppy... just trying to dive right in =)
`
$page = new Page();
$page->title = "Add a New Item";
$page->DisplayHeader();
$page->DisplaySidebar();
if (isset($_POST['submit']))
{
// make short variable names
$name = trim($_POST['name']);
$level = intval($_POST['level']);
$slot = strtolower($_POST['slot']);
$hp = intval($_POST['hp']);
$mana = intval($_POST['mana']);
$mvs = intval($_POST['mvs']);
$int = intval($_POST['int']);
$wis = intval($_POST['wis']);
$str = intval($_POST['str']);
$dex = intval($_POST['dex']);
$con = intval($_POST['con']);
$p_ac = intval($_POST['p_ac']);
$m_ac = intval($_POST['m_ac']);
$saves = intval($_POST['saves']);
$hit = intval($_POST['hit']);
$dam = intval($_POST['dam']);
$queryOk = 1;
if (empty($name) || empty($level) || empty($slot))
{
echo '<h3>Please enter all the required fields</h3>';
$queryOk = 0;
}
// Instantiate database object and connect
# $db = new mysqli('*host*', '*user*', '*pass*', '*database*');
// Check connection to
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database, try again later';
}
$query = "INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)".
"V ALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
$result = $db->query($query);
if (!$result)
{
echo '<h3>Error: Item was not entered. (Your webmaster sucks)</h3>';
}
else {
echo "<p>The items \"$name\" was successfully entered into the database. <a href=\"equipment.php\>Back to Equipment or add another item.</a></p>";
}
$db->close();
}`

If the space in V ALUES is actually in your code that would cause your query to fail
UPDATE
If that isn't the cause of the error use $mysqli->error to see what error occurred.
if (!$result)
{
echo '<h3>'$mysqli->error' (Your webmaster sucks)</h3>';
}

int is a reserved word in mysql, and you're using it as a fieldname. You'll have to escape it with backticks:
INSERT INTO ... (..., `int`, ...)
^---^-- escapes
your query:
INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)
^^^^--- problem here
VALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
^^^^^---NOT here

Related

GET ID after submitting form

Im trying to get the ID when I insert a SQL, I've tried to get the last. I've tried to echo out the ID in the hidden html form but without any success
As you see I've $sql that inserts INTO log_create, but from that I need to receive the ID which is created, it need to be echoed
$id = $db->real_escape_string(trim($_POST['id']));
$name2 = preg_replace('/\s+/', '', $name);
$game = $db->real_escape_string(trim($_POST['game']));
$info = $db->real_escape_string(trim($_POST['info']));
$mobname = $db->real_escape_string(trim($_POST['mobname']));
$sql = "INSERT INTO log_create(`id`, `name`, name2, game, monster, info)VALUES('$id', '$name', '$name2', '$game', '$mobname', '$info')";
if($result=$db->query($sql))
{
$log = $db->query("SELECT itemname FROM `log_mitem` WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
if($log1 = $log->fetch_object());
{
while($loco = $log->fetch_object())
{
$item = "$loco->itemname";
$logss = "INSERT INTO log_drops(`item`, `mobname`, `game`, `log_id`, `log_name`)VALUES('$item', '$mobname', '$game', '$id', '$name')";
if($result1 = $db->query($logss));
}
}
echo '<p>';
echo 'Your droplog has been created! Check your droplog category to start hunting!';
echo '</p>';
} else { echo 'Something went wrong!';
}
Thismay help you, maybe?
Good luck! :-)
EDIT: My bad, I should have said what was that, instead of linking directly.
It's the mysqli::$insert_id variable.
It stores the last ID created by the last used "INSERT" sentence.
...
if($result=$db->query($sql))
{
echo "New ID: "+$db->insert_id+"<br />";
...
Or wherever you want to use it.
Make sure to store it before inserting anything else, or it'll be replaced.

How to Put multiple Arrays into one database table

0I have three arrays... example:
phonenums
[0] 555-5555
[1] 555-4444
[2] 555-3333
types
[0] cell
[1] home
[2] work
notes
[0] a note
[1] the babysitters name
[2] call before 6pm
They come from a form with dynamically added inputs, so the number of rows is arbitrary.
I want to put these arrays into a table in MySQL, using PHP
Table name: customerphones
id
customer_id
phone
type
notes
I can get any single array into the database fine, but, when it comes to putting in all three to coordinate with each other (ex: each row[0] to be in one row of the database table)....I'm stuck! I keep rewriting it in different loops or whatnot, and it comes out wrong every time.
I can post my code if it helps explain my situation further. I am just looking for a "concept" here though, to point me in the right direction.
Should I combine the arrays somehow?, or put them into a loop? I don't know!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is my solution I came up with (as requested). I'm sure it is not practical at all...and there is probably a much better way to do it. But it got my desired result.
// ~~~ Get variables from the form submitted
$phonenums = $_POST["phone"];
$types = $_POST["type"];
$notes = $_POST["notes"];
// ~~~ Queries for Inserting Customer Phone Numbers
$querynum = "INSERT INTO customerphones";
$querynum .= "(customer_id, phone)";
$querynum .= "VALUES (?, ?)";
$stmtnum = mysqli_prepare($db, $querynum);
$queryty = "UPDATE customerphones SET ";
$queryty .= "type = ? ";
$queryty .= "WHERE customer_id = ? AND phone = ?";
$stmtty = mysqli_prepare($db, $queryty);
$queryno = "UPDATE customerphones SET ";
$queryno .= "notes = ? ";
$queryno .= "WHERE customer_id = ? AND phone = ?";
$stmtno = mysqli_prepare($db, $queryno);
// Loops for executing the queries to insert phone numbers
// (I scraped this together b/c I couldn't get other methods to work...Change this later)
$n = 0;
foreach($phonenums as $rowph) {
mysqli_stmt_bind_param($stmtnum, 'is', $custid, $rowph);
mysqli_execute($stmtnum);
$rct = 0;
foreach($types as $rowty) {
if($rct == 0) {
$x = $types[$n];
mysqli_stmt_bind_param($stmtty, 'sis', $x, $custid, $rowph);
mysqli_execute($stmtty);
$rct++;
}
} // End Update Phone Type
$rct = 0;
foreach($notes as $rowno) {
if($rct == 0) {
$x = $notes[$n];
mysqli_stmt_bind_param($stmtno, 'sis', $x, $custid, $rowph);
mysqli_execute($stmtno);
$rct++;
}
} // End Update Phone Notes
$n++;
} // End foreach loops
Well, I'm gonna take a shot in the dark here.
Using PDO with PreparedStatements, MultipleIterator and ArrayIterator:
$dbh = new PDO("mysql:host=localhost;dbname=YOUR_DATABASE;", "root", "");
$sth = $dbh->prepare("INSERT INTO customerphones(phone, type, notes) VALUES(:phone, :type, :note)");
$m = new MultipleIterator();
$m->attachIterator(new ArrayIterator($phonenums), 'phones');
$m->attachIterator(new ArrayIterator($types), 'types');
$m->attachIterator(new ArrayIterator($notes), 'notes');
foreach($m as $row){
$sth->bindParam(":phone", $row[0]);
$sth->bindParam(":type", $row[1]);
$sth->bindParam(":note", $row[2]);
$sth->execute();
}
I'm assuming that you're using a local MySQL server, and your server's root account isn't password protected.
This works like this:
Create a new PDO connection with some parameters;
Prepare a statement with some placeholders for an insert;
Create an Iterator to unite the arrays;
Attach all the arrays to the iterator;
Go through all the iterations of the iterator: Every iteration returns a array with a phone number, a type and a note;
Bind all the elements of the current iteration to the placeholders of the statement and then execute it.
But please post what you're using to connect to the DB, then I'll refactor my answer.
using mysqli:
$host = 'your_host';
$user = 'your_user';
$pass = 'your_pass';
$db = 'your_database';
$mysqli = new mysqli($host, $user, $pass, $db);
// Check connection mysql
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$sql = 'INSERT INTO customerphones(phone, type, notes) VALUES(?,?,?)';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sss', $phone, $type, $note);
$index = 0;
while(COUNT($phonenums) - 1 >= $index){
$phone = $phonenums[$index];
$type = $type[$index];
$note= $note[$index];
$stmt->execute();
$index++;
}

PHP: Running mysql_query if data from $_POST matches data in table

I hope my title isn't completely confusing. I'd like to start by saying I am in now way a programmer and am an amateur with PHP and MySQL, which I use for online gaming. I have been tirelessly working at this for a few days, with no success. I've been toying with the idea of asking for help here, hoping folks go easy on me and don't completely rip apart my code! Like I said, I'm an amateur.
Basically, what I'm trying to do is match the $horsename data from my $_POST array with name in my table called horses. If they do not match it will add a horse with that name into the horses table. If they do match, it will simply continue on and add the data from the $_POST array into the results table for each line.
The issue I'm getting, (and I've toyed with this multiple times, with a different issue arising each time) is even if the $horsename matches name in the horses table, it tries to add a new horse into the horses table. It also is not moving onto the next line of data and will try to add the same horse over and over again. (Hope that makes sense!)
I'm pasting most of my code from this page below, just in case it's something earlier in my code causing this issue. Please note, a portion of this code is not my own and I am working on it for someone else, so if things are not completely uniform in a couple of spots, that is why. The portion I'm working on is what I've mentioned above.
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$results = str_replace("\r", '', trim($_POST['news']));
$data = array();
$lines = explode("\n", $results);
foreach ($lines as $place) {
if (!empty($place)) {
$data = array();
$detail = explode(",", $place);
if (!empty($detail)) {
$id = '';
$show = $_POST['show'];
$year = $_POST['year'];
$association = $_POST['association'];
$chpoints = $_POST['chpoints'];
$rchpoints = $_POST['rchpoints'];
$ttpoints = $_POST['ttpoints'];
$chearnings = $_POST['chearnings'];
$rchearnings = $_POST['rchearnings'];
$ttearnings = $_POST['ttearnings'];
$horsename = stripslashes(trim($detail[0]));
$placement = stripslashes(trim($detail[1]));
$class = stripslashes(trim($detail[2]));
if($placement === 'CH'){
$points = $chpoints;
}
else if ($placement === 'RCH') {
$points = $rchpoints;
}
else {
$points = $ttpoints;
}
if ($placement === 'CH') {
$earnings = $chearnings;
}
else if ($placement === 'RCH') {
$earnings = $rchearnings;
}
else {
$earnings = $ttearnings;
}
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
if (isset($_POST['news'])) {
$query="INSERT INTO `results` (`id`, `show`, `year`, `place`, `name`, `class`, `points`)
VALUES ('$id','$show','$year','$placement','$horsename','$class','$points')";
mysql_query($query) or die ('Error updating database: ' . mysql_error());
echo "Result successfully added!" ;
}
};
};
};
To take a snip-it from above, this is the place I'm having the issues:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
If anything from the page where news is coming from is needed, please let me know.
Thanks in advance!
The problem is that you are querying the database for a list of every horse name. You're iterating through that list and each time the names don't match, you're inserting the new name. What you need to do instead is to query for the specific name.
SELECT * FROM horses WHERE name = '$horsename'
If this returns a row, then you know the horse is already in the database. If it returns no rows, then you can safely insert once. By the way, you'll want to properly escape your input to prevent SQL injections so don't use my code verbatim.
Try this:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
$i = 0;
$horsename = "";
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
$i = 1;
}
}
if($i == 1) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}

Give another random int if number exists in database (PHP)

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!

How to do a INSERT with two different loops?

Update
I have updated my code according to phant0m's suggestion. It still doesn't quite work yet, though: question_id is always 0 in the database, even though it's not in the array:
var_dump($_POST['question_id'])
array(2) { [0]=> string(2) "22" [1]=> string(2) "23" }
The query:
string(122) "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES
(1, 4, 0, 'answer1'),
(1, 4, 0, 'answer4')
This is the new code:
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES";
foreach($_POST['answer'] as $id => $answer){
// don't use $_REQUEST!
$course_id = (int) $_POST['course_id'][$i];
$student_id = (int) $_POST['student_id'][$i];
$question_id = (int) $_POST['question_id'][$i];
$answer = mysql_real_escape_string($answer);
$sql_data[] = "($course_id, $student_id, $question_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
var_dump($sql);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
//replaced die with else clause
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
Initial question:
I have a problem adding the values of an array into a mysql database. The thing is
I have two loops and if I add the INSERT in one of the then the other one gives the wrong value. But if I echo inside each loop it gives the right values.
At the moment it adds two double rows of each value where I only want one row of each value.
Here is my code:
<?php
require_once("settings.inc.php");
// require_once("student_session.inc.php");
session_start();
for ($d = 0; $d <= count($_POST[answer]); $d++) {
$answer = $_POST[answer][$d];//I want to insert this value
//echo $answer;
$ids = $_REQUEST['question_id'];
foreach ($ids as $value) {
//echo $value; //and this value into the INSERT
$sql = "INSERT INTO student_score(answer) VALUES ('$answer')";
$results = mysql_db_query($dbName, $sql, $connect);
}
}
if (!$results) {
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
die;
}
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
die;
?>
You're using the wrong variable:
"INSERT INTO student_score(answer) VALUES ('$answer')";
You comment that the variable you'd like inserted is called $value, so you meant to write:
"INSERT INTO student_score(answer) VALUES ".
"('".mysql_real_escape_string($value)."')";
(mysql_real_escape_string is to prevent SQL injection attacks)
make use of MySQL transactions:
PHP + MySQL transactions examples
Also can you post the output of the following?:
print_r($_POST); and print_r($_POST[answer]);
Using $_REQUEST is bad Idea. either use POST or GET explicitly!
Your code does not make much sense.
This might more closely resemble what you want it to do:
// you will not want <=, that will create an index error upon the last
// iteration, also, you need to quote the key!
// This is fixed:
//for ($d = 0; $d < count($_POST['answer']); $d++) {
// this is a better way
// this assumes, that the indices of the POST array nicely correspond with each
// other.
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(question_id, student_id, course_id, answer) VALUES";
foreach($_POST['answer'] as $id => $anwer){
// don't use $_REQUEST!
$question_id = (int) $_POST['question_id'][$i];
$student_id = (int) $_POST['student_id'][$i];
$course_id = (int) $_POST['course_id'][$i];
$answer = your_escape_function($answer)
$sql_data[] = "($question_id, $student_id, $course_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
//replaced die with else clause
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
Attention
This code is mostly based on guesswork and assumptions what you want it to do.
You need to have a function that properly escapes your code based on whether magic_quotes are enabled. Simply calling mysql_real_escape_string()as suggested in the other answer is incorrect.
Please note that mysql_* functions are outdated. Consider using parameterized queries using PDOs or myqsli.
PS: do not use $_REQUEST.

Categories