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.';
}
Related
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.
I need to read and process (for example add a "2" at the end of IDs + some other things...) and re-insert at least 2000 records form MySQL with PHP.
It's not possible to do it with a SQL Query...
The problem is when we click on the Go button, it processes almost 500 records but then we see a "Server Internal 500" error! but in localhost we don't have any problem...
Is there a way to do this with these limited resources in our customer websites?
Another question: What causes this problem? What resource needs to be more? RAM? CPU?...?
Here is the code:
(We should read all courses of a semester and all course selections and copy them to the new semester)
foreach ($courseList as $courseInfo)
{
$ccode=$courseInfo['ccode'];
$lid=$courseInfo['lid'];
$pid=$courseInfo['pid'];
$clid=$courseInfo['clid'];
$cgender=$courseInfo['cgender'];
$descriptive_score=$courseInfo['descriptive_score'];
$final_capacity=$courseInfo['final_capacity'];
$days_times=$courseInfo['days_times'];
$exam_date=$courseInfo['exam_date'];
$exam_place=$courseInfo['exam_place'];
$ccourse_start_date=date("Y-m-d H:i:s");
$ccomment=$courseInfo['ccomment'];
$cid=$courseInfo['cid'];
$majors=$course->GetCourseMajorsList($cid);
$scList=$course->GetCourseScoreColumnsList($cid);
$courseScoreColums=array();
foreach ($scList as $scProp)
{
$courseScoreColums[$scProp['scid']]=$scProp['scid'].','.$scProp['cscfactor'];
}
$tid = $term->LastTermID();
$counts = $course->AddCourse($ccode.'2',$tid,$lid,$pid,$clid,$majors,$courseScoreColums,$cgender,$descriptive_score,$final_capacity,$days_times,NULL,$exam_place,$ccourse_start_date,$ccomment,$aid);
if ($counts==1)
{
$new_cid = $course->LastCourseID();
$cs = new ManageCourseStudents();
$query = " WHERE `".$table_prefix."courses`.`cid`=$cid ";
$courseStudentList = $cs->GetCourseStudentList($query,'');
foreach ($courseStudentList as $csInfo)
$cs->AddCourseStudent($csInfo['uid'],$new_cid,$csInfo['lvid'],$aid);
}
}
$str = "select * from tableName"; //replacing * by table columns is a good practice
$result = $conn->query($str);
while($arr = $result->fetch_array(MYSQLI_ASSOC);)
{
$strr1 = " INSERT INTO tableName ( `id` , `title` , `des` ) //add more
VALUES ( '".$arr['id']."2', '".$arr['something']."' //add as you require
";
if($conn->query($strr1) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
}
this could duplicate every data in your database
I almost managed to split the different arrays and to prepare them in the table in the MySQL database, I'll explain the situation:
On the main page, the user has the ability to add and remove rows in a table. The table for each line carries with it these inputs:
input1.name = "product[]";
input2.name = "seller[]";
input3.name = "description[]";
input4.name = "quantity[]";
input5.name = "priece[]";
so if the user inserts two rows in each array will be included descriptions of two products, for example:
product: "PS3", "PS4";
seller: "AMAZON", "SONY";
description: "100Gb", "200Gb";
quantity: "1", "2";
price: "100", "200";
This is the layout table:
http://www.mediafire.com/view/ux0su8ssdixfmgc/Cattura2.JPG
The problem arises. I capture the data entered via a post, but I can't distribute these data on several lines. I want you to PS3 both into the first row of MySQL table, and PS4 in the second row of the table. Until now arrays are instantiated only on the first line, in this way, however, there is only one product. It is therefore necessary to prepare each box in the appropriate row of the array. I do not know if I was clear, but I would like to achieve something like this:
http://www.mediafire.com/view/d6f6ahy834jv0p2/Cattura.JPG
Obviously, the data in table I've entered manually and not through code. Was it right for you to understand.
This is the code that I currently use to send multiple arrays on different lines, but it doesn't work.
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
$row_data[] = "('$product', '$seller', '$description','$quantity', '$priece', '$user')";
}
if (!empty($row_data))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.implode(',', $row_data);
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
if I understood it well this is how it should work
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
array_push($row_data, "('$product', '$seller', '$description','$quantity', '$priece', '$user')");
}
foreach($row_data as $value){
if (!empty($value))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.$value;
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
I'm constructing a webpage to submit camera bookings to a MYSQL database. This webpage has a html frontend that forwards it to the following PHP page, which then submits that information to the MYSQL
Currently the client wishes for there to be no way of making duplicate bookings of the Cameras. To fulfill this, I have constructed the following PHP page, which checks if the chosen camera in the html frontend ($_POST[camera]) is the same as anything in the $result_array array. The code is as follows:
<?php
$con = mysql_connect("****","*****","*******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("****", $con);
$query = "SELECT Camera FROM T_Bookings";
$result = mysql_query($query) or die ("no query");
$result_array = array();
while($row = mysql_fetch_array($result)) {
$result_array[] = $row;
}
$fixed_array = array_keys($result_array);
if (in_array($_POST[camera],$result_array)){
$x = 1;
$y = 2;
}
if($x + $y == 3){
echo "Camera already booked!";
}
else {
mysql_query("INSERT INTO T_Bookings (F_Name, L_Name, Camera, Bag, Cable, Tripod, MemoryCard, Date, Authorised)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[camera]','$_POST[bag]','$_POST[cable]','$_POST[tripod]','$_POST[memory]','$_POST[date]',)");
echo "1 record added";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
}
mysql_close($con);
?>
However, it is consistently placing a booking even if these conditions aren't met. Why is this the case?
Thanks,
Dayne.
mysql_fetch_array($result) returns an array like
array('Camera' => 'Whatever')
So change the line below to read
$result_array[] = $row['Camera'];
There's a fundamental flaw in your logic. You have a requirement for a unique value and the current implementation does not provide any such guarantee (learn about ACID on Wikipedia: http://en.m.wikipedia.org/wiki/ACID).
You're in luck though. MySQL happens to provide just what you need with little effort. Create a unique index on the Camera column (http://dev.mysql.com/doc/refman/5.5/en/create-index.html). Then don't check for a previous entry with the same name. Simply try to do an insert. MySQL will return an error which is easily handled and your code just became simpler, easier to read and manage.
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