I have a strange thing over here. I'm trying to insert a value in my database but it's not working for some reason. I have this code:
PHP:
<input type='file' name='images[]' />
<input type="text" name="newproject_name" id="tags"/>
<input type='text' name='order[]' value='$b' />
$project = new Project();
$project->photo = $_FILES['images']['name'][$key];
$project->order = $_POST['order'][$key];
$projectnaam = $_POST['newproject_name'];
if($project->createProject($_DB)) {
echo "OK";
} else {
echo "NOT OK";
}
}
FUNCTION:
class Project {
public function createProject($db) {
$sql = "INSERT INTO tblProject (
project,
photo,
order) // If you remove this line, the function is working
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."' // If you remove this line, the function is working
)";
return $db->insert($sql);
}
}
Strange thing is, when I delete the order-lines, the function is working just fine. I really don't know what I'm doing wrong...
ORDER is a reserved word. If you use backticks around the column name you should be good:
$sql = "INSERT INTO tblProject (
`project`,
`photo`,
`order`)
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."'
)";
I suggest you change the order column name to position or display_order.
Related
I'm trying to check posts to see whether they mention another user, by using #username. I want to replace that with a link to the user's profile.
This is what I've got... I haven't got any errors, but usernames just go through as text without the link. I feel like $getUsers/$gU isn't returning the results to $checkString, but I can't see anything wrong.
function post()
{
global $me;
if($_POST['message'])
{
$getUsers = mysql_query("SELECT user_id, user_name FROM users");
while($gU = mysql_fetch_array($getUsers))
{
$checkString = strpos($_POST['message'], "#".$gU['user_name']."");
if($checkString !== false)
{
$replaceFrom = "#".$gU['user_name']."";
$replaceTo = "<a href=\'/user.php?id=".$gU['user_id']."\'>".$gU['user_name']."</a>";
$checked = str_replace($replaceFrom, $replaceTo, $_POST['message']);
}
else
{
$checked = $_POST['message'];
}
}
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$checked."', UNIX_TIMESTAMP())");
index();
}
else {
echo "
<form action='?action=insert' method='post'>
<input type=text name=topic maxlength=40>
<br><textarea name=message cols=80 rows=9></textarea>
<br><input type='submit' STYLE='color: black; background-color: white;' value='Submit' class='btn'>
</form>
";
}
}
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$_POST['message']."', UNIX_TIMESTAMP())");
should be
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$checked."', UNIX_TIMESTAMP())");
As your user table will eventually grow, I'd suggest compiling a set of potential usernames by searching for #(\w+), preparing a statement looking for that username, iterating through the results and replacing all instances for every returned row with the link.
I think you could have simplify your question by excluding the MySQL part. From what I understand you are trying to replace user mention with an HTML anchor tag.
Instead of looping through all the available users you can use preg_replace_callback() to check if any tagged user exists in system.
Please review the example code below. To simplify things I have created two functions. parseTag() will inject the HTML anchor link if the user exist, otherwise the original tag will be kept. getUserId() will return the user id it exists in the system instead:
<?php
function parseTag($tagInfo){
list($fullTag, $username) = $tagInfo;
$uid = getUserId($username);
if ($uid) {
return "<a href='/url/to/user/{$uid}'>{$fullTag}</a>";
}
return $fullTag;
}
function getUserId($username){
$userList = [null, 'john', 'mary'];
return array_search($username, $userList);
}
$comment = "Hello #john, #doe does not exists";
$htmlComment = preg_replace_callback("/#([\w]+)/", "parseTag", $comment);
echo $htmlComment;
Output:
Hello <a href='/url/to/user/1'>#john</a>, #doe does not exists
I need a help with my code; somehow my code creates two rooms (it inserts two rows into a table at once), I don't know why.
(I need to require an id for every insert to know in which house we create a new room. My database contains table 'house' and table 'room'. Table 'room' has a field 'house_id' which is a foreign key with a field 'id' in table 'house'.)
That is my php page:
<?php
// turn autocommit off
mysqli_autocommit($con, FALSE);
// fetch the houses so that we have access to their names and id
$query = "SELECT name, id
FROM house";
$result = mysqli_query($con, $query);
// check query returned a result
if ($result === false) {
echo mysqli_error($con);
} else {
$options = "";
// create an option
while ($row = mysqli_fetch_assoc($result)) {
// $options .= "".$row['name']."";
$options .= "<option value='".$row['id']."'>";
$options .= $row['name'];
$options .= "</option>";
}
}
include('templates/add_room.html');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = mysqli_real_escape_string($con, $_POST["price"]);
$house = mysqli_real_escape_string($con, $_POST["house_id"]);
$query = "INSERT INTO room (price, house_id)
VALUES ('$price', '$house')";
// run the query to insert the data
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
echo "<script type= 'text/javascript'>alert('New room created successfully with the id of {$con->insert_id}');</script>";
mysqli_commit($con);
} else {
echo "There was a problem:<br />$query<br />{$con->error}";
mysqli_rollback($con);
}
}
//free result set
mysqli_free_result($result);
?>
and that is my html template with form:
<h2>Add new room</h2>
<form action='' method='POST'>
<fieldset>
<label for='price'>Price:</label>
<input type='number' name='price'>
</fieldset>
<fieldset>
<label for='house_id'>House:</label>
<select name='house_id' required>
<option value='' disabled selected>Select house</options>
<?php echo $options; ?>
</select>
</fieldset>
<button type='submit'>Add</button>
</form>
It inserts 2 rows because of your using the query function twice:
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
So you'll need to change that conditional statement to:
if ($result) {
By the way, use a prepared statement, it's safer than real_escape_string():
https://en.wikipedia.org/wiki/Prepared_statement
You are inserting it twice
first here:
// run the query to insert the data
$result = mysqli_query($con, $query);
then here:
// check if the query went ok
if ( $con->query($query) ) {
Remove the first one and you should be fine, or check on the result of the first one and remove the second one.
Not 100% certain, but it looks like you run INSERT query twice. Once here:
$result = mysqli_query($con, $query);
and once a moment later when you try to check for something. you inadvertently use the OOP style when you are apparently trying to check for something
if ( $con->query($query) ) {
<?php
require "config.php";
/*
CREATE TABLE `addnews` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`auther` VARCHAR( 255 ) NOT NULL ,
`title` VARCHAR( 255 ) NOT NULL ,
`content` LONGTEXT NOT NULL
) ENGINE = MYISAM ;
*/
$a = $_POST['author'];
$t = $_POST['title'];
$c = $_POST['content'];
if(isset($_POST["add"]) and $_POST["add"] == "news"){
$insert = mysql_query('INSERT INTO addnews
(author,title,content)
VALUES
("$a","$t","$c")') or die("error");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
echo "
<form action='".$_SERVER['PHP_SELF']."' method='post'>
Author : <input type='text' name='author' /><br>
Title : <input type='text' name='title' /><br>
Content : <textarea name='content'></textarea>
<input type='submit' value='Add news' />
<input type='hidden' name='add' value='news' />
</form>
";
mysql_close($connectdb);
?>
i am getting error from this statment i think
if(isset($_POST["add"]) and $_POST["add"] == "news"){
$insert = mysql_query('INSERT INTO addnews
(author,title,content)
VALUES
("$a","$t","$c")') or die("error happend while trying to add information to database");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
output is : error happend while trying to add information to database
and no problem with config.php file (the file that connect to database)
i am using phpmyadmin
strings in sql are surrounded by ' (single quote) , not by " (double quote)
strings in php will act two ways
those in ' (single quote) will write literally as tyou typed them ($a stays $a - not $a value)
those in " (double quote) will interpret values inside - so $a will be substituted with $a's value
when failing DB operation - it is usually useful to see what was wrong - use mysql_error for that
Use && instead of the actual word and:
if(isset($_POST["add"]) && $_POST["add"] == "news"){
$insert = mysql_query("INSERT INTO addnews
(author,title,content)
VALUES
('$a','$t','$c')") or die("error happend while trying to add information to database");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
Here you go try this one
if(isset($_POST["add"]) and $_POST["add"] == "news"){
$insert = mysql_query('INSERT INTO addnews
(author,title,content)
VALUES
("'. $a .'","'. $t .'","'. $c .'")') or die("error happend while trying to add information to database");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
used "'. $a .'" instead "$a".
I think the query statement is wrong,
Double quotes inside the single quotes is not valid in php.
So you will change the quotes in query like below code,
$insert = mysql_query("INSERT INTO addnews
(author,title,content)
VALUES
('$a','$t','$c')") or die("error");
try this..:-)
Please do the correction in your code like as follow:
$insert = mysql_query("INSERT INTO addnews
(author,title,content)
VALUES
('$a','$t','$c')") or die(mysql_error($link));//Where $link mysql resource object
You will get the answer why Mysql not inserting your data.
I have a table as so:
TABLE click_count
(
count int(3)
);
which is currently an arbitrary number. I have this php script with an html button which should just increment the number by one. The SQL query works in php my admin but gets an error when it's ran on the page.
<?php
require("config.inc.php");
if(!empty($_POST)){
$query = "UPDATE click_count
SET count = count + :submit_1
";
$query_params_ = array(
'submit_1' => $_POST['count']
);
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["message"] = "Vote Cast!";
echo json_encode($response);
} else {
?>
<form action="vote.php" method="post">
Count:<br />
<input type="number" name="submit_1" value="1" />
<br /><br />
<input type="submit" value="Cast Vote" />
</form>
<?php
}
?>
You have to change your array key to match the one in preparedStatement. Like this:
$query_params_ = array(':submit_1' => $_POST['count']);
Indeed, you are refering to $query_params in the execute() method, but you are defining $query_params_ (with underscore in the end).
count is a reserved keyword of mysql, see: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
try to enclose it into accents, like this:
UPDATE click_count
SET `count` = `count` + :submit_1
";
I am trying to record the results of a car race, but I want to be able to enter all of the results for the race at once (rather than doing it one by one) but I just cannot seem to get it to work.
Code below:
INPUT FORM:
{
$reID = $row['reID'];
$racerID = $row['racerID'];
echo "<tr>";
echo "<td>$reID<input type='hidden' name='reID' value='$reID'>";
echo "<td>$racerID<input type='hidden' name='racerID' value='$racerID'>";
echo"<td><input type='text' name='rank'>";
echo"<td><input type='text' name='timetaken'>";
}
SQL INSERT FORM:
$rank=$_POST['rank'];
$timetaken=$_POST['timetaken'];
$reID=$_POST['reID'];
$racerID=$_POST['racerID'];
$sql = mysql_query("INSERT INTO Racing (rank, timetaken, reID, racerID) VALUES ('$rank', '$timetaken', '$reID', '$racerID')");
$result = mysql_query($sql);
How this works is, I will select a race, then a specific event within that race, then that will display all the racers and I can enter their rank and time taken. At the same time the hidden inputs (racer no and raceevent will go into the database for each result too).
So I am trying to just enter all the ranks and timetaken for all racerIDs at once, can someone help me complete that please.
Thanks.
EXTRA:
$reID = $_GET['reID'];
$result = mysql_query("SELECT * FROM RaceEventRacer WHERE reID = $reID");
while ($row = mysql_fetch_assoc($result))
First of all u have to fix some issues with ur php form generation...
all of ur input elements are going to have the same name attribute...
correct it first
-use something like this
$cv=0;
while () {
.......................
.......................
echo "<input name='racer_'.$cv>"; // in each repetition new name value, not the same
$cv++;
}
Instead of having name='reID' you should have name='reID[]', the same withthe other fields. And the future code would look like this:
$ranks = $_POST['rank'];
$timetakens = $_POST['timetaken'];
$reIDs = $_POST['reID'];
$racerIDs = $_POST['racerID'];
$sql = "INSERT INTO Racing (rank, timetaken, reID, racerID) VALUES";
$values = array();
foreach($ranks as $key => $rank) {
$values[] = "('$rank', '{$timetakens[$key]}', '{$reIDs[$key]}', '{$racerIDs[$key]}')";
}
$sql .= implode(', ', $values);
$query = mysql_query($sql);