PHP cannot insert data - php

When I using the following code I cannot insert data. It shows the following error message:
[An error occured while inserting your data. Please try again later.You have an error in your SQL syntax: check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 10]
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['userlevel'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['userid'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['userid'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
//after a lot of work, the query succeeded!
echo 'You have successfully created your new topic.';
}
}
}
}
`

You missed to add quotes around each string:
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
'" . mysql_real_escape_string($_POST['topic_cat']) . "',
'" . $_SESSION['userid'] . "'
)";
You have to add single quotes around your second mysql_real_escape_string. (And also around your $_SESSION['userid'] if it contains a string.)

<pre>
<?php
$con = mysql_connect( 'localhost', 'root','' );
if (!$con)
{
die( 'Could not connect: ' . mysql_error() );
}
mysql_select_db( "stack",$con );
$_SESSION['userlevel']= 1;
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['userlevel'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
$user =1;
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ", ". $user. "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",1
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
//after a lot of work, the query succeeded!
echo 'You have successfully created your new topic.';
}
}
}
}
?>
</pre>
i am using same script and it is working. please check your session if it creates

Your sql query is breaking here enclose your string and date values with "'"
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(), <--- enclose with ."'"

Related

How to update database's value after pressing button?

I am currently working on my assignment, I am trying to create a ban system for users, I wanna update the value of Deleted in my database to 1 whenever I press the submit button, I tried many on youtube videos but has not given any process
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
$row2 = mysqli_fetch_assoc($result);
if ($row2['Admin'] == 0) {
echo '<div class="alert alert-warning" role="alert">
Unfortunately you do not have access to this page
</div>';
}
else {
$query = " SELECT * FROM Users WHERE Admin = 0";
$result = mysqli_query($link, $query);
echo '<div class="container">';
echo '</div>';
echo '<div class="container"><table class="table table-primary table-hover">';
echo '<tr><th>' . 'NameID' . '</th><th>' . 'Name' . '</th><th>' . 'Email' . '</th><th>' . '</tr>';
while ($row2 = mysqli_fetch_assoc($result)) {
echo '<tr><td>' . $row2['UserID'] . ' </td><td> ' . $row2['FirstName'] . ' ' . $row2['LastName'] . ' </td><td> ' . $row2['EMail'] . ' </td><td> '
. '<input type="submit" name="submit" class="btn btn-primary btn-xs" value="BAN">' . ' </td></tr>';
}
if (isset($_POST['submit'])) {
echo '</table>' . '</div>';
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
}
}
}
You define $query2 but never execute it. This is a common mistake.
Tip: Don't declare SQL as strings and then run it later, get in the habit of supplying the query as a direct argument to prepare().
For example:
$stmt = $link->prepare('UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID`=?');
$stmt->bind_param('i', $id);
$stmt->execute();
You don't run the $query2, do it like this
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
mysqli_query($link, $query2);
}

Restricting Duplicate results in php mysqli

While selecting rows the data should be shown as:
but on the running code it is as:
My Codes:
<?php
$link = mysqli_connect("localhost", "root", "", "trial");
if(!$link){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$term = 'd';//mysqli_real_escape_string($link, $_REQUEST['term']);
if(isset($term)){
$sql = "SELECT * FROM rolls WHERE Place LIKE '%" . $term . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
if(mysqli_num_rows($result) > 1000){
echo "<p>There are many results please be more specific</p>";
}
else{
while($row = mysqli_fetch_array($result)){
echo "<p><a href='#". $row['Place'] ."'>" . $row['Place'] . "</a></p>";
}
mysqli_free_result($result);
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
On trying
$sql = "SELECT * FROM rolls WHERE Place LIKE '%" . $term . "%' LIMIT 1";
it only displays MANDYA, rest all are skipped
If you just want to display the place, use DISTINCT for showing unique values. Check out this query.
$sql = "SELECT DISTINCT(Place) FROM rolls WHERE Place LIKE '%" . $term . "%'";

Variable not recognised in INSERT but working in SELECT

Basically I am using the variable $shopid to recognise which shop has been chosen. I am now trying to create a comment system to enable each shop page to be commented on. My SELECT query is recognising $shopid and enabling me to use it, when I try to use the same variable in my INSERT, it simply posts 0.
<?php
database connection
session_start();
if (isset($_SESSION['logged'])){
$s_userID = $_SESSION['userID'];
$shopid = $_GET['page_id'];
$str_shops = '';
//bring shop data
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE shopID = '$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='result'><strong>" .
$row['image1'] . "<br><br>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br>" .
$row['website'] . "<br><br>" .
$row['openinghours'] . "<br><div class='justifytext'>" .
$row['more'] . "<br><br></div><strong>What do they sell?</strong><br><br><div class='justifytext'>" .
$row['sold'] . "<br><br></div></div>";
}
//post comment
mysqli_select_db($db_server, $db_database);
$comment = $_POST['comment'];
if ($comment != '') {
$query = "INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', '$shopid', '$comment')";
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$commentmessage = "Thanks for your comment!";
}
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server)); $i = 0;
while($row = mysqli_fetch_array($result)){ $i++;
$str_comments.= "<p><div id='displaycomments'>" . $row['username']. ", " .
$row['commdate'] . ": <br>" .
$row['comment'] . "</div>";
}
}
echo $str_shops;
echo $commentmessage;
echo $str_comments;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? I'm not getting an error, it is simply adding 0 to the shopID column in my table.
My guess would be that your shopID column would be of INT datatype and you are passing a string to it in your insert statement, thats why 0 is being stored.Try again by removing the single quotes around $shopid, like this-
INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', $shopid, '$comment')"
^^^^^^^ remove the single quotes

Sum Up Points Based on Questions Answered

The code is of a short-answer quiz for a uni course. What I'd like to do is to match students' response to answer stored in database. A matching answer (or keywords) counts as a point. I'm having trouble counting the total points. The preg_match() results are already correct. Here is the code:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
$qno = $_POST['q_no'];
?>
<head></head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="590" border="1" cellpadding="2" align="center">
<?php
//db query to obtain i_id - to insert to RESULT table
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_assoc($query_i);
$ins_id = $data_i['i_id'];
//echo $ins_id;
//$correct = 0;
$total = 0;
$arr_ind = 1;
$atext = array(1);
$ans = array(1);
for($i=1;$i<=$qno;$i++){
$repStr = str_replace("1", $i, "answer_1");
//echo "Question ". $i .": ". $repStr;
$ans[] = $_POST[$repStr];
//echo $ans;
$sql_check = "SELECT q_ans FROM question WHERE q_id='$i'";
$query_ch = mysql_query($sql_check) or die("MySQL Error: " . mysql_error());
$data_ch = mysql_fetch_assoc($query_ch);
$atext[] = $data_ch['q_ans'];
// insert answer to table
//$sql_eval = "INSERT INTO eval_set (s_id, q_id, response, response_value, created) VALUES ('" . $id . "', '" . $i . "', '" . $ans . "', '" . $correct . "', CURDATE())";
//mysql_query($sql_eval) or die ("Error: " . mysql_error());
}
// insert result to table
//$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ('" . $total . "','" . $id . "','" . $ins_id . "')";
//mysql_query($sql_result) or die ("Error: " . mysql_error());
// db query for questions
$sql_q = "SELECT q_id, q_no, q_text, q_ans, q_help FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions & answers
$rad = 1;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
echo "<tr><td width='20' align='center' valign='top'><label><br><input name='q_no' size='1' type='hidden' value=". $data_q['q_no'] .">". $data_q['q_no'] ."</label></td>";
echo "<td><p align='justify'>". $data_q['q_text'] ."<br />";
if(preg_match_all("/". $ans[$arr_ind]. "/i", " . $atext[$arr_ind] . ")){
echo "Something matches";
$total = total + 1;
}
//else if (preg_match("/^$/", " . $atext[$arr_ind] . "))
//echo "Empty string";
else
echo "Wrong";
echo "<p align='justify'><b>YOUR ANSWER: </b>". $ans[$arr_ind]. "</p>";
echo "<p align='justify'><label><b>SUGGESTED ANSWER:</b> <br><input name='answer_".$rad."' type='hidden' value=''>". $atext[$arr_ind] . "</label></p>";
$rad++;
$arr_ind++;
}
mysql_free_result($query_q);
include("dbconn.php");
echo "</table>";
echo "<h2>" . $total . " questions correct. - Answer Review</h2>";
echo "</form>";
?>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
// close db connection
mysql_close($dbconn);
?>
You are missing a $ in:
$total = total + 1;
Or just use:
$total++;

SQL Query succeeds but no information

Okay so my code works pretty well so far, it all goes through, my only problem is that when I try and print the unordered list and it's contents I get nothing. When I view my source code I have <ul> </ul>. There's a space, so surely something is happening.
This is my code, I have commented it slightly but what's happening is obvious:
$uname = mysqli_real_escape_string($link, $_SESSION['Username']); //Get username ready
$sql = mysqli_query($link, "SELECT * FROM users WHERE Username = '" . $uname . "'"); //SQL Query result
if(!$sql)
{
echo "Error retrieving User ID. Please try again. MySQL Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
$uid = $row['UserID']; //Obtain UserID
}
else
{
echo "Error: " . mysqli_error($link) . "<br />" . $uname . " / " . $sql . " / " . $uid;
}
mysqli_free_result($sql);
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
else
{
echo "Error: " . mysqli_error($link);
}
Where am I going wrong? The only thing it doesn't do is actually pick up any results and I've put some data into the table so there are entries! Otherwise it would say there aren't any. I've reversed this so it shows the message if there aren't 0 entries and that works. What am I doing wrong guys?
Thanks in advance.
You are fetching the result twice. Instead, only fetch the result in the while loop:
<?php
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
else{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
?>
See this link for more information regarding mysql_fetch_assoc

Categories