I'm trying to create a very simple web app that checks if an element is inside the database.
If the element is located at least one time in the DB, then echo "YES", otherwise if the element doesn't exist just echo "NO".
Here's my code :
$mysql = mysqli_connect(/* can't share anything here */) or die ("ERROR CONNECTING TO THE DB");
if(isset($_POST['submit'])) {
$theAddress = $_POST['url'];
$result = "SELECT * FROM data WHERE url = " . $theAddress;
$query = mysqli_query($mysql, $result);
if (!$query) {
printf("Error");
} else {
printf("NO ERROR");
}
The problem here is that PHP always echo "Error". Why?
In order to execute SQL queries successfully you need to put the string values inside quote.
So your query will be:
$result = "SELECT * FROM data WHERE url = '" . $theAddress . "'";
You need quotes around the value because it's a string.
$result = "SELECT * FROM data WHERE url = '" . $theAddress . "'";
But it would be better if you learned to use prepared queries with mysqli_stmt_bind_param(), then you don't have to worry about this.
Try with prepared statements like this:
$stmt = mysqli_stmt_init($mysql);
if (mysqli_stmt_prepare($stmt, 'SELECT * FROM data WHERE url = ?')) {
mysqli_stmt_bind_param($stmt, "s", $theAddress);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
Documentation:
http://us.php.net/manual/en/mysqli-stmt.prepare.php
http://us.php.net/manual/en/mysqli-stmt.get-result.php
Related
All I want to do is get the firstname result from this function, but it feels it's too much code to do that based on session id.
//query_functions.php
function find_name_by_id($id) {
global $db;
$sql = "SELECT firstname FROM admins ";
$sql .= "WHERE id='" . db_escape($db, $id) . "' ";
$sql .= "LIMIT 1";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$name = mysqli_fetch_assoc($result); // find first
mysqli_free_result($result);
return $name; // returns an assoc. array
}
// admin.php
id = $_SESSION['admin_id'];
$name = find_name_by_id($id);
// what is the shortest way to get this $name result?
To do this properly using prepared statements you actually need more code than that:
function find_name_by_id($db, $id) {
$stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->free_result();
return $row[0];
}
I'm not sure what confirm_result_set is so I left it out.
Let's pretend that $db was a PDO object:
function find_name_by_id($db, $id) {
$stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
$stmt->execute([$id]);
return $stmt->fetchColumn();
}
Much less code involved. And for a higher-level API this will be abstracted to a single line of code.
In reality for all cases you'd want to do some error checking, account for no records being returned, etc. Also you should avoid global variables, they're very poor form. Put your code into a class or just use dependency injection as I've done.
looked around, saw a lot of MySQL answers but not MySQLi..
Im attempting to return 1 line of my choosing.
at the moment I can return only the first line.
What im trying to get to is, have my main database be linked by ID, when you click the ID, a closer look at the record is on another page..
<?php
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info ORDER BY id";
$record = mysqli_query($connect, $query);
#$num_results = mysqli_num_rows($record);
$row = mysqli_fetch_assoc($record);
$fname = $row['name'];
$surname = $row['surname'];
print $fname;
print $surname;
?>
In order to do what you're asking, first create a list of users:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info ORDER BY id";
$record = mysqli_query($query, $connect);
while($row = mysqli_fetch_assoc($record)){
$user = $row['name'] . ' ' . $row['surname'];
echo '' .$user . '</br>';
}
The will create a list of all your users which look like:
Bart Simpson</br>
Matt Damon</br>
And so on.
When you click the user's link in the original page, it should be processed by the code in user.php:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info WHERE id = ?"; // returns one line identified by id - you can use something else if you're guarateed the value is unique in your table
$stmt = mysqli_prepare($connect, $query);
mysqli_stmt_bind_param($stmt, 'i', $_GET['uid']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name, $surname);
mysqli_stmt_fetch($stmt);
I'll bet you can guess what happens now, can't you? That's right, you can echo out the data for the individual user on this page:
$user = $name . ' ' . $surname;
echo $user;
NOTES:
The connection code could be placed in a separate file and included in pages where needed.
You could write a function to handle every query you write.
In order to prevent the possibility of SQL Injection I have used prepared statements for MySQLi. Even escaping the string is not safe!
Generally I would be a lot more consistent with my coding, performing queries the same way each and every time. doing so will reduce troubleshooting time as well as making your code easier for others to read.
I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.
I want to make a query that ends in LIKE value%, but for some reason, there is an error with it.
$_GET['letter'] contains the starting letter that I want to use in my query.
For example if its 'a', my query will be ...WHERE name LIKE 'a%'.
My code:
$sql = sprintf("SELECT id, name, username, email FROM users WHERE name LIKE '" . ($_GET['letter']) . "%'");
The error I get is: PHP Warning: sprintf(): Too few arguments
And then of course: PHP Warning: mysqli::query(): Empty query
Thanks in advance.
Don't even consider taking this route. Use prepared statements with PDO or mysqli instead.
if(isset($_GET['letter']) && strlen($_GET['letter']) > 0) {
$letter = $_GET['letter'] . '%';
$sql = "SELECT id, name, username, email FROM users WHERE name LIKE ?";
$query = $con->prepare($sql);
$query->bind_param('s', $letter);
$query->execute();
$query->bind_result($id, $name, $username, $email);
while($query->fetch()) {
echo $id . '<br/>';
// and others
}
// alternate version with mysqlnd installed
// $results = $query->get_result();
// while($row = $results->fetch_assoc()) {
// echo $row['id'];
// }
} else {
echo 'please provide for search value';
}
I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";