<?php
$sql = "SELECT MAX(REQUEST_ID) AS REQUEST_ID FROM TBL_REQUEST;";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
echo "alert('DataBase Error');";
}
else{
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
$newReqId=$row['REQUEST_ID']+1;
}
$sql = "INSERT INTO TBL_REQUEST VALUES(".$newReqId.",\'ISSUE\',\'Test\',\'Test\',\'NSNS05\',1);";
$newsql = $sql;
$stmt = sqlsrv_query( $conn, $newsql );
if( $stmt === false) {
echo "alert('Not Inserted '+assoc_id+' ".$stmt." '+' ".$newsql." ');";
}
else{
echo "alert('Inserted '+assoc_id+' ".$stmt."');";
}
?>
in this above code i have used 2 SQL statements the first one is a select statement which works fine and fetches data from the table, but when i execute the Insert on the same table its not working...
INSERT INTO TBL_REQUEST VALUES(4016,'ISSUE','Test','Test','NSNS05',1);
thats the string which is
why are using "" between "" you should ' ' for $newReqId
$sql = "INSERT INTO TBL_REQUEST VALUES(".$newReqId.",\'ISSUE\',\'Test\',\'Test\',\'NSNS05\',1);";
Related
<?php require_once('connection.php');
session_start();
if (isset($_POST['Submit']))
{
$answ = $_POST['answ'];
$email = $_SESSION['email'];
$insert = "INSERT INTO answerList (answ,queID,email) SELECT questionList.queID FROM questionList " ;
$result = mysqli_query($con, $insert);
if (!$result) {
echo "<script>alert('ERROR !!!!! '); location='faq.php';</script>";
}
else {
echo "<script>alert('Successful Post'); location='faq.php'; </script>";
}
}
?>
I have 3 table
table 1: users(email, password)
table 2: question(questionID, questionContent, email)
table 3: answer(answerID, answerContent, questionID, email)
how can i connect questionID into table 3?
i already do the login and add question sql . but how can i add the answer to current question with logged email?
a table have question. and each question have answer button
You could use <input type='hidden' name='questionId' value='<?php echo $value>'>
For each question you'll have to set $value to the questionID.
When the answer is submited you'll do:
if (isset($_POST['Submit']))
{
$answ = $_POST['answ'];
$email = $_SESSION['email'];
$questionId = $_POST['questionId'];
$insert = "INSERT INTO `answerList`(`answer`, `email`, `questionID`) VALUES ('$answ','$email','$questionId[value-3]')" ;
$result = mysqli_query($con, $insert);
if (!$result) {
echo "<script>alert('ERROR !!!!! '); location='faq.php';</script>";
}
else {
echo "<script>alert('Successful Post'); location='faq.php'; </script>";
}
}
My PHP code works properly but the problem is, when I press the back button, the alert dialog again shows up. The alert dialog is needed while logging in, and it works properly. But when I press the back button, it again shows the alert box.
<?php
if($_POST){
$host = "localhost";
$user = "root";
$pass = "";
$db = "erp";
$userId = $_POST['myusername'];
$password = $_POST['mypassword'];
$conn = mysqli_connect($host,$user,$pass,$db);
$query = "SELECT * from user where user_id='$userId'";
$result = mysqli_query($conn,$query);
$num = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($row["user_id"]==$userId){
if($row["password"]==$password){ //when user_id and password
//match, go to check
//usertype
switch($row["user_type_id"]){
case 1: session_start();
$_SESSION['erp']='true';
header('location:acc_setting.php');
break;
case 2: session_start();
$_SESSION['erp']='true';
header('location:dashboard.php');
break;
case 3: session_start();
$_SESSION['erp']='true';
header('location:c_course.php');
break;
}
}
else{
echo '<script language="javascript">';
echo 'alert("Invalid Password")';
echo '</script>';
}
}
else{
echo '<script language="javascript">';
echo 'alert("Invalid Username")';
echo '</script>';
}
}
?>
Ignoring the security issues I mentioned in comments and to specifically answer your subsequent question how do I set a session var and redirect it to same page perhaps the following might help. I simplified in a couple of places but essentially the same for the most part.
<?php
if( $_POST ){
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'erp';
$conn = mysqli_connect( $host, $user, $pass, $db );
$destinations=array(
1 => 'acc_setting.php',
2 => 'dashboard.php',
3 => 'c_course.php'
);
$userId = $_POST['myusername'];
$password = $_POST['mypassword'];
/*
This should be a prepared statement
-> $sql='select `password` from `users` where `user_id`=?';
-> $stmt=$conn->prepare( $sql );
-> $stmt->bind_param('s',$userid );
etc etc
The passwords should be hashed in the db using password_hash
and verified in PHP using password_verify
NEVER store plain text passwords
*/
$query = "SELECT * from user where user_id='$userId'";
$result = mysqli_query($conn,$query);
$num = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if( $row['user_id']==$userId ){
/*
this should be password_verify
*/
if( $row['password']==$password ){
$_SESSION['erp']='true';
exit( header( sprintf( 'Location: %s', $destinations[ $row['user_type_id'] ] ) ) );
} else{
$_SESSION['error']='Invalid Password';
}
} else{
$_SESSION['error']='Invalid Username';
}
/*
An error must have occurred, redirect back to oiginal page
*/
exit( header( sprintf('Location: %s', $_SERVER['SCRIPT_NAME'] ) ) );
}
?>
Then, in the original page where the form is
<form>
<!--
various form elements
-->
<?php
if( !empty( $_SESSION['error'] ) ){
echo $_SESSION['error'];
unset( $_SESSION['error'] );
}
?>
</form>
So I am trying to do an history for my site but when i do the query select with the jquery variable it doesn't work. HERE is the table that shows the values from db and here is the pop up box that opens to show details but I want to show the values from each row that I click
Here is the jquery code:
var idocorrencia;
$(document).on("click","#listagem tr td a", function(e){
e.preventDefault();
idocorrencia = $(this).parent().attr("idlista");
$("#listagem caption").text($(this).text());
console.log(idocorrencia);
alert(idocorrencia);
$.post( "historico.php", { idoc: idocorrencia })
$.ajax({
method:"POST",
url:"historico.php",
data:{idoc : "idlista"},
dataType: 'json',
});
});
Here is the php:
$id = $_POST['idoc'];
$result = mysqli_query($conn, "SELECT id FROM ocorrencia where id=$id");
$row = mysqli_fetch_assoc($result);
$idoc = isset($_POST['idoc']) ? $_POST['idoc'] : $row['id'];
Try to do it like this:
if (isset($_POST['idoc'])) {
$id = $_POST['idoc'];
$result = mysqli_query($conn, "SELECT id FROM ocorrencia where id='" . mysqli_real_escape_string($conn, $id) . "'");
if($result!==false && mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
$idoc = $row['id'];
}
}
UPDATE
and here is the same script with prepared statements:
if (isset($_POST['idoc'])) {
$statement = mysqli_prepare($conn, "SELECT id FROM ocorrencia where id=?");
mysqli_stmt_bind_param($statement, 's', $id);
$id = $_POST['idoc'];
mysqli_stmt_execute($statement);
$result = mysqli_stmt_get_result($statement);
if ($result !== false && mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$idoc = $row['id'];
}
}
Here I have used procedural style, as the original script was like that. But it can be easily rewritten in object oriented style.
i want to fetch data from my database which is linked to the website,i have created a search box,whenever i enter a particular value in search box,it should display all the related content from the database.i have done the following code,it is not fetching the data from the database,it just shows a blank screen.
<?php
define('db_name','njgh');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
session_start();
$link=mysql_connect(db_host,db_user,db_password);
if(!$link)
{
die('couldnot connetc:'.mysql_error());
}
$db_selected=mysql_select_db(db_name,$link);
if(!$db_selected)
{
die('cant connect to db');
}
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM database WHERE Site_ID = '$value'";
$result = mysql_query($qry);
print_r($result);
mysql_query function return resource ID not your data , use mysql_fetch_array, mysql_fetch_object to get data
$value = ($_POST['searchtext']);
$result = mysql_query("SELECT * FROM database WHERE Site_ID = '$value'");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_* has been removed entirely as of PHP 7.0. Prevent SQL injection and use the mysqli statement class.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "njgh";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['searchtext'];
/* create a prepared statement */
if($stmt = $conn->prepare("SELECT * FROM database WHERE Site_ID =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['db_table_field_name'];
}
//or
$row = $result->fetch_assoc();
print_r($row);
} else {
}
/* close statement */
$stmt->close();
}
/* close connection */
$con->close();
?>
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.
Hope this will work for you......
<?php
define('db_name','sports');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
$link=mysqli_connect(db_host,db_user,db_password,db_name);
if(!$link)
{
die('couldnot connect:'.mysql_error());
}
function clean($str) {
$link=mysqli_connect(db_host,db_user,db_password,db_name);
$str = #trim($str);
if(get_magic_quotes_gpc())
$str = stripslashes($str);
return mysqli_real_escape_string($link, $str);
}
if(isset($_POST['searchtext'])){
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM cricket WHERE id = '$value'";
$qrydb = mysqli_query($link, $qry);
while($row=mysqli_fetch_array($qrydb)){
$name = $row['name'];
}
echo $name ;
}
?>
<body>
<form method="post">
<input type="text" name="searchtext">
<input type="submit" name="submit">
</form>
</body>
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I am trying to build a click button that increments value of the item in the database. I am using UPDATE method for this.
The problem is that whenever the update query is run, the value it takes from the databse to increment (or decrement) is zero. (0+1 = 1, 0-1 = -1)
require_once("C:/xampp/htdocs/Selfie/database/dbcontroller.php");
$db_handle = new DBController();
$image_id = $_POST["image_id"];
$active_user_id = $_POST["active_user_id"];
$query = "SELECT user_image_id from users where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['user_image_id'] == $image_id) {
echo "own image";
}
else
{
$query = "SELECT image_id from hearts where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
if ($row['image_id'] == $image_id) {
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE users SET user_like ='' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "just unlike";
}
else
{
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $row['user_image_id'];
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . " where user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
echo "unlike then like";
}
}
else
{
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . "' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "image liked successfully.";
}
}
This is my jQuery code:
function test_click(i_image_id, i_heart_id, i_active_user_id) {
var active_user_id = i_active_user_id;
var image_id = i_image_id;
var heart_id = i_heart_id;
jQuery.ajax({
url: "../Selfie/validations/add_like.php",
data: {
active_user_id: active_user_id,
image_id: image_id
},
type: "POST",
success: function(data) {
if (data == "own image")
{
alert('You are trying to like your own image You NARCISSIST');
}
else if (data == "just unlike")
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
alert('just unlike');
}
else
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
$("#" + heart_id).removeClass("animated rubberBand");
$("#" + heart_id).toggleClass("btn-heart-red animated bounce fa-heart-red");
}
alert(data);
}
});
}
This image_hearts='image_hearts'+1 remove the quotes; that's a column you're wanting to update and not the string literal. The same thing goes for 'image_hearts'-1
Check for errors on your queries, which would have helped you here.
http://php.net/manual/en/function.mysql-error.php
Plus, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0 and removed as of PHP 7.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Footnotes:
If I may quote Marc's comment:
"in other words. 'image_hearts' + 1 is string literal plus integer, and unless that string literal contains digits at the start of it, will simply become 0 + 1 – Marc B"