PHP and Mysql trying to run code on DB [duplicate] - php

This question already has answers here:
mysqli_real_escape_string not working properly
(2 answers)
Closed 5 years ago.
Good Day
I am new to html, php I am trying to set up a page to run a sql query to move data from one table into another one. The trouble I am having is that I require a user to input a date that needs to pass to the query.
I have checked on the net and viewed the question that this is marked as a duplicate of. And am still unable to get this working.
My Html is as follows for the submit part.
<div class = "boxed">
<p> First Date to be used for comparasion</p>
<form method="post">
Date1: <input type="text" name="date1"/>
<input type="Submit" value="submit"/>
</form>
</div>
My Php is
<?php
session_start();
include_once 'include/dbconf.php';
if(isset($_POST['date1']))
$d1 = mysqli_real_escape_string($_POST['date1']);
$sql1 = "insert ignore into compare2 SELECT * FROM Compare where Date =
'$d1'";
$sqldata = mysqli_query($sql1,$conn) or die ('error updaing Table');
echo "Table updated";
mysql_close($con)
?>
My include/dbconfig.php works as I use it on another page and connect succesfully to the DB.
It looks like my query doesn't get the user defined input passed to it.
I don't get any errors either in the httpd error.log.
You advise and help would be most appreciated.
Updated PHP
<?php
session_start();
include_once 'include/dbconf.php';
if(isset($_POST['date1']))
{
$d1 = mysqli_real_escape_string($conn, $_POST['date1']);
$sql1 = "insert ignore into compare2 SELECT * FROM Compare where Date =
'$d1'";
$sqldata = mysqli_query($conn, $sql1) or die ('error updaing Table');
echo "Table updated";
}
mysqli_close($conn)
?>
Still not running the sql to update the table.

Change your code to:
session_start();
include_once 'include/dbconf.php';
if(isset($_POST['date1'])) {
$d1 = mysqli_real_escape_string($conn, $_POST['date1']);
$sql1 = "insert ignore into compare2 SELECT * FROM Compare where Date = '$d1'";
$sqldata = mysqli_query($conn, $sql1) or die ('error updaing Table');
echo "Table updated";
}
mysql_close($con);

Related

How can I read data from MySQL in different project which is saved by another app?

I have two separate applications that are working with the same database in MYSQL. The first app in Nodejs and modify data in the database, when I want to read data from the second app coded in PHP, the data looks hidden (no result to select). I can see the data in the database, and I can get the result from the same query that I have in PHP. When I am adding data manually, it is accessible from PHP app.
Code in Node.js
const mysql = require('mysql')
const mysqlconnection = mysql.createConnection({
host:'172.16.X.X',
user:'XXX',
password:'XXXX',
database:'ramen'
});
var sql = "INSERT INTO challenge_usersolved (user, challenge_Id, username)
VALUES (?,?,?)";
var values = [challenge.name , challenge.difficulty, usname];
mysqlconnection.query(sql, values,(err, row)=>{
})
PHP side Code is:
<?php
$db = mysqli_connect('172.16.X.X', 'ramen', 'XXX', 'ramen', '3306');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT sum(challenge_Id)*100 as score, username FROM (SELECT
Distinct user, challenge_Id, username FROM challenge_usersolved) as T
GROUP BY username;";
$result = mysqli_query($db, $query);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " .
mysql_error();
}
$rs = mysqli_fetch_assoc($result);
echo "<html><head><title>Score Board</title></head><body>";
echo "<table align='center' border='1px' style='width:300px; line-height: 30px'>";
echo"<tr><th colspan='2'>Students Score</th></tr><t><th>Username</th> <th>Score</th></t>";
while($rows=mysqli_fetch_assoc($result) ){
echo "<tr><td>{$rows["username"]}</td><td>{$rows["score"]}</td></tr>";
}
echo "</body></html>";
?>
Your
$rs = mysqli_fetch_assoc($result);
line loads the first record and you do not do anything with it. When your code arrives to the while loop, the next (second) row is attempted to be loaded, but you have a single row as you described in the comment section. The solution seems to be to remove the
$rs = mysqli_fetch_assoc($result);
line.

Providing Count from MySQL using PHP

I am trying to output a count of the number of results I have in a survey. The query itself ($sql) seems correct, because I do not get the error I have included, when I know that works. What isn't happening is the output. I have all my PHP tags and my database connection in place just fine, so I haven't included them here. They function just fine. What I need to know is how to get this outputted. This echoing for a count had worked for a previous PHP database set, but it is not working for this one.
My database has just ONE table, named survey. 'sur_cnt' is an auto-increment field that adds up whenever a new input is added to the database. My page output comes out blank, so I believe something is wrong with the echo, but I'm not sure what.
$sql = "SELECT COUNT(`sur_cnt`) FROM Survey";
$num = mysqli_query($db, $sql) or die('Error
querying database.');
$num_results = $result->num_rows ;
echo $num_results ;
try this query
because COUNT() using with groub by cluase
$sql = "SELECT * FROM Survey"; //remove count()
$result= mysqli_query($db, $sql) or die('Error querying database.');
$num_results = mysqli_num_rows($result) ;
echo $num_results ;
You need to use some form of fetch method to actually retrieve the count from your SQL statement - just the same as any other type of data from the database...
$sql = "SELECT COUNT(`sur_cnt`) FROM Survey";
$num = mysqli_query($db, $sql) or die('Error querying database.');
$row = mysqli_fetch_array($num) ;
echo $row[0] ;

Retrieving data from MySQL database using $_SESSION username

I am new at PHP and I'm trying to create a profile page whereby the user is able to view their information which they inserted when signing up to the website.
At first I'm attempting this with just their first name, so that whoever is logged in can see what first name they have saved on the database.
I have a included "checklog.php" page which includes
<? php session_start(); ?>;
And in my page, when i use;
echo $_SESSION['username']
The user's username is printed out fine.
So i've tried to apply this in mysqli query in order to print out their first name from the database like this;
<?php
if($db_server){
$query = "SELECT firstname FROM users WHERE username=$_SESSION['username']";
$result = mysqli_query($db_server, $query) or
die(mysql_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
echo $row['firstname'];
}
}
mysqli_free_result($result);
?>
But I get an error on line 15 which is the SQL statement, can someone tell me what I'm doing wrong in my statement?
First of all add session_start(); in the top of the PHP code..
<?php
session_start();//<-- Here
Second.. rewrite your query like this..
$query = "SELECT firstname FROM users WHERE username= '".$_SESSION['username']."'";

Display row in mysql table when a user enter id

I want to display a row when a user enter his id and after submit.
My code is not working correctly. Please rectify this.
search-form.php is looking like this.
</html><body>
<form method="GET" action="search.php">
Keyfield <input type="text" name="search"> <br><br>
<input type="submit" value="submit">
</form></body>
</html>
and
search.php looking like this.
<?php
$connection = mysql_connect('localhost','user','pass') or die ("Couldn't connect to server.");
$db = mysql_select_db('db', $connection) or die ("Couldn't select database.");
$search=$_GET['search'];
$fetch = 'SELECT * FROM `table` WHERE `ID` = "'.$search.'"';
echo "<table margin=auto width=999px border=1>";
echo "<tr><td><b>ID</b></td><td><b>Name</b></td><td><b>Telephone</b></td><td> <b>E-mail</b></td><td><b>Couttry Applying for</b></td><td><b>Visa-Category</b> </td><td><b>Other Category</b></td><td><b>Passport No</b></td><td> <b>Remarks</b></td></tr>";
for($i=0;$i<$num;$i++)
{
$row=mysql_fetch_row($fetch);
echo "<tr>";
echo"<td>$row[0]</td>";
echo"<td>$row[1]</td>";
echo"<td>$row[2]</td>";
echo"<td>$row[3]</td>";
echo"<td>$row[4]</td>";
echo"<td>$row[5]</td>";
echo"<td>$row[6]</td>";
echo"<td>$row[7]</td>";
echo"<td>$row[8]</td>";
echo"</tr>";
}//for
echo"</table>";
?>
Display when a user enter his id and submit. But this code doesn't display row with id.
Rectify this.
Thanks.
you are missing mysql_query statement.You should execute the query before fetching the result
modify like
$sql= 'SELECT * FROM table WHERE ID = "'.$search.'"';
$fetch = mysql_query($sql);
A few points:
mysql_connect is obsolete, do not use it. Use PDO instead for example.
$fetch = 'SELECT * FROMtableWHEREID= "'.$search.'"' leads to the most common and severe security flaw : SQL injection. Please read about this (google)
Where do you "fetch" the result of your query ?
About point 3, assuming the fact that you will use PDO, please read http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html

Connecting html form to php page according to primary key

Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.

Categories