Cannot echo result from mysql - php

All I need is to produce a row. I've looked at all the samples and I cannot for the life of me get the right information. Hence help is required please.
Connection to DB in the usual way. Here is my code for the query.
$sql = "SELECT * FROM table WHERE `u_password` = $pword AND `user` = $uname LIMIT 1";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
I've got a count in there and it produces a result of 1.
The error I get is
'Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result'
Help would be appreciated.

The error
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
Almost always means that the query failed for some reason, thus $result = mysqli_query returns FALSE rather than a mysql_result object so anything that then tries to use $result as an object will not work for obvious reasons.
The issue with your query is that text column data must be wrapped in quotes like this
$sql = "SELECT *
FROM table
WHERE `u_password` = '$pword' AND `user` = '$uname' LIMIT 1";
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
You should use parameterized queries to avoid this.
$sql = "SELECT *
FROM table
WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
// its also a good idea to check the staus of a prepare
// and show the error if it failed, at least while testing
if ( $stmt === FALSE ) {
echo mysqli_error($mdb);
exit;
}
$stmt->bind_param('ss', $pword, $uname );
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['seeking'];

You need to use prepared statements (in actuality you could get it to work by quoting your strings but prepared statements are much better). Like so:
$sql = "SELECT * FROM table WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
$stmt->bind_param("ss",$pword,$uname);
if ($stmt->execute()) {
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
} else { /* something went wrong */ }

Related

How do I check if a table is empty or already my query didn't match any results

I want an if-statement that only runs, when there are no rows in the table or if existing rows dont match a specific parameter from my input. I tried this way:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql);
if(!$result)
{ ... }
From my thinking this should execute the if-statement on the first time I want to add something to the database and if the $currentURL does not exist in existing data. But this does not seem to work the way I think it does. How would you do this? Maybe I'm handling the $result wrong, because if I test the sql-query inside phpmyadmin this shows the right result (no rows).
The correct way to do this would be to use prepared statement and fetch the results into an array. You can fetch all rows into an array using fetch_all()
$stmt = $conn->prepare("SELECT * FROM images WHERE imageURL = ?");
$stmt->bind_param('s', $post["media_url"]);
$stmt->execute();
// Get result and then fetch all rows from the result object
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// Then check if you have any rows at all using a simple if statement
// Negate it using ! to check if the array is empty
if (!$result) {
// no results found
}
I guess, that $conn is a PDO connection? In that case, the method $conn->query() returns an object of type PDOStatement. See https://www.php.net/manual/de/class.pdostatement.php
The method does NOT return the result set.
Instead you can use the PDOStatement object, to fetch the results:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetchAll();
if(empty($result))
{ ... }
In case you are using mysqli, the object returned by query() is this: https://www.php.net/manual/en/class.mysqli-result.php
So the code would be:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
if(empty($result))
{ ... }
Please also note: Your code is highly insecure! You should use prepared statements to prevent sql-injection:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = :currentUrl";
$stmt = $conn->prepare($sql);
$stmt->execute(['currentUrl' => $currentURL]);
$result = $stmt->fetchAll();
if(empty($result))
{ ... }
sanitize input against sql injection (or better - use prepared statements and param binding)
$sql = "SELECT * FROM images WHERE imageURL = '".$conn->real_escape_string($currentURL)."'";
mysqli query returns true on success (even empty dataset is success), use num_rows instead:
if ( $result->num_rows === 0 ) { ... }

Correct Syntax to Add ORDER BY to SQL Query

How can I add ORDER BY field to the end of this SQL query
$sql = "SELECT item_id,field FROM item WHERE department=".$catid;? I can't get the syntax right due to the PHP variable at the end...
I tried $sql = "SELECT item_id,field FROM item WHERE department=".$catid ORDER BY field; but obviously that didn't work
You can fix your syntax error like this, using another concatenation operator . to append the ORDER BY clause:
$sql = "SELECT item_id,field FROM item WHERE department=".$catid." ORDER BY field";
As long as $catid is an integer, that will work, but it may leave you open to SQL injection, dependent on the source of the value in $catid.
Best practice is to use a prepared query. For MySQLi, something like this:
$sql = "SELECT item_id,field FROM item WHERE department=? ORDER BY field";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $catid); // change to 's' if $catid is a string
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with results
}

call to undefined function execute()

bellow is my code.Error shown is like
fatal error: call to undefined function execute() on line 21,
how could i solve this problem?
<?php
include 'config/dbconfig.php';
include 'lib/function.php';
include 'helper/helper.php';
$db = new rootfunc();
$fm = new formate();
if(!empty($_POST['name']) or !empty($_POST['email']) or !empty($_POST['password1']) or !empty($_POST['dob']) or !empty($_POST['gender']) ){
$name = $fm->validation($_POST['name']);
$email = $fm->validation($_POST['email']);
$password = $fm->validation($_POST['password1']);
$dob = $_POST['dob'];
$gender = $fm->validation($_POST['gender']);
$query = $pdo->prepare("SELECT * FROM user_table WHERE name = ? AND email = ?");
$query = execute(array($name,$email));
$numRow = $query->rowCount();
if(!$numRow){
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$query = $pdo->prepare($query);
$query->execute(array($name,$email,$password,$dob,$gender));
echo "Congrates, please login..";
}else{
echo "name and email exist..";
}
}
?>
In both cases you are overwriting $query:
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$query = $pdo->prepare($query);
You need to give the execution a different variable to hold the object, for example:
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$result = $pdo->prepare($query);
$result->execute(array($name,$email,$password,$dob,$gender));
In addition you should allow users to use the passwords / phrases they desire. Don't limit passwords.
While you're working with passwords never store them as plain text! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
I also noticed this in your code
$numRow = $query->rowCount();
Since the query is a SELECT query it will not work with rowCount()
From the docs:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
For SELECT when you are not doing a COUNT() query you can return the number of rows like this after you execute the query;
$rows = $result->fetchAll();
$num_rows = count($rows);
In your case it is not necessary to check the count though - just check to make sure the query executed which is enough to get into your conditional statements.

How to solve Illegal string offset ['id'] in php?

I'm sorry if this is a duplicate question but I don't know how to solve my problem. Every time I try to correct my error I fail. My code is:
if (isset($_GET["comment"])) {$id = $_GET["comment"];}
$query = "SELECT * FROM posts WHERE id = {$id['$id']};";
$get_comment = mysqli_query($con, $query);
Can anybody correct the code to not show an error anymore and tell me what did I wrong?
Try this:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = "SELECT * FROM `posts` WHERE `id` = " . intval($id);
The use of intval will protect you from SQL injection in this particular case. Ideally, you should learn PDO as it is extremely powerful and makes prepared statements much easier to handle to prevent all injections.
An example using PDO might look like:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = $pdo->prepare("SELECT * FROM `posts` WHERE `id` = :id");
$query->execute(array("id"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC); // for a single row
// $results = $query->fetchAll(PDO::FETCH_ASSOC); // for multiple rows
var_dump($result);
First of all you should prevent injestion.
if (isset($_GET["comment"])){
$id = (int)$_GET["comment"];
}
Notice, $id contanis int.
$query = "SELECT * FROM posts WHERE id = {$id}";
Assuming your $id is an integer and you only want to make the query if it is set, here's how you could do it using prepared statements, which protect you from MYSQL injection attacks:
if (isset($_GET["comment"])) {
$id = $_GET["comment"];
$stmt = mysqli_prepare($con, "SELECT * FROM posts WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $get_comment);
while (mysqli_stmt_fetch($stmt)) {
// use $get_comment
}
mysqli_stmt_close($stmt);
}
Most of these functions return a boolean indicating whether they were successful or not, so you might want to check their return values.
This approach looks a lot more heavy duty and is arguably overkill for a simple case of a statement containing a single integer but it's a good practice to get into.
You might want to look at the object-oriented style of mysqli which you might find a little cleaner-looking, or alternatively consider using PDO.

Unable to concatenate sql in pdo statement [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> SQLSTATE[42000]: Syntax error or access violation: 1064 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 ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";

Categories