Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';
Related
I am trying to figure out how to use this in a loop. Any help will be appreciated.
$conn = mysql_connect("localhost", "some_user", "password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("some_db")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT favid FROM ajaxfavourites";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
}
mysql_free_result($result);
Currently it displays results as:
116677889922
I need them to show them as (the way they are displayed in DB):
1166
7788
9922
PS I am aware that this function is deprecated, I am just trying to fix one of my older sites.
choose One of these ways:
echo $row["favid"]."<br>";
echo $row["favid"]."\n";
echo $row["favid"].PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
echo "\r\n";
}
You can simply echo the value with '<br/>' or '<p>' like following:
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"] . '<br/>';
}
OR
while ($row = mysql_fetch_assoc($result)) {
echo '<p>' . $row["favid"] . '</p>';
}
Also you can just put all favid into array and then in another loop, can customize how to show them, like following:
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row["favid"];
}
foreach($ids AS $idv) {
echo '<p>' . $idv . '</p>';
}
When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs
The following query is returning the result I expected:
$link=mysqli_connect('localhost','user','pass');
if(!$link){
echo "No connection!";
exit();
}
if (!mysqli_set_charset($link, 'utf8'))
{
echo 'Unable to set database connection encoding.';
exit();
}
if(!mysqli_select_db($link, 'database')){
echo "No database";
exit();
};
$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");
while ($row = $res->fetch_array()) {
echo " cenas = " . $row['rules'] . "\n";
};
But, since I'm using Joomla 2.5.16 and I'm trying to keep its syntax, I tried:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " cenas = " . $row['rules'] . "\n";
};
This isn't working. It is only displaying the text " cenas =".
What is wrong with this code?
Try the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('rules'))
->from($db->quoteName('#__viewlevels'))
->where($db->quoteName('id')." = ".$db->quote('10'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result) {
echo " cenas = " . $result->rules;
}
Version 4:
I have taken away the pull down menu for now, I just want the info to be posting correctly.
As it shows with the first line fab1 shows #2, in the second line it shows 1, --None-- instead of 2, Andy Khal. If anyone can figure out why, it be appreciated. I've done about as much as I can to figure this out and I'm lost.
<?php
// Connect to the database.
require_once('tb/connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("MySQL failed to connect: " . mysqli_connect_error());
}
// Create the SQL query
$testbed = "SELECT * FROM testbed";
$user = "SELECT * FROM user";
// Execute the SQL query and store the result set in
// the $result variable.
$testbed = mysqli_query($dbc, $testbed) or die("Failed to execute query on tesbed table: " . mysqli_error($dbc));
$user = mysqli_query($dbc, $user) or die("Failed to execute query on user table: " . mysqli_error($dbc));
// Read the results.
$row = mysqli_fetch_assoc($testbed);
if(!$row)
{
echo 'Query failed<br />';
}
else
{
echo "Query for Testbed Fabricator is : " . $row["fab1"] . "<br />";
}
$row = mysqli_fetch_assoc($user);
if(!$row)
{
echo 'Query for Testbed Fabricator failed<br />';
}
else
{
echo "Query for User ID # is : " . $row["userid"], $row["user"] . "<br />";
}
// Free the result set.
mysqli_free_result($testbed);
mysqli_free_result($user);
?>
Yes it is. You can specify the selected value with the selected keyword as a html attribute.
<option value="Username" selected>Username</option>
That makes this:
while($row = $result->fetch_assoc())
{
$user = $row['user'];
echo '<option value="' . $user . '"';
if($user is known)
{
echo ' selected';
}
echo '>' . $user . '</option>\n';
}
Update
In this snipped $choosen is the selected user's name.
echo'<div id="fab1">';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$mysqli->select_db('user');
$result = $mysqli->query("SELECT * FROM user");
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
echo '<option value="' . $row['user'] . '"';
if($row['user'] == $choosen)
{
echo ' selected';
}
echo '>' . $row['user'] . '</option>\n';
}
echo "</select>\n";
echo '</div>';
I am trying to make the different the different rows have line breaks but its not working.
How is this done!? Please check my code below
Thanks guys!
James
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '$search%' AND lastname LIKE '$searchterm'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
}
mysql_free_result($result);
?>
<?php echo $row["name"];?>
<br>
<?php echo $row["lastname"];?>
<br>
<?php echo $row["email"];?>
Beats me what you find so hard about it:
while ($row = mysql_fetch_array(...)) {
echo ...
echo '<br>';
}