how can i get a field on a mysql table? - php

Im a php/mySQL newbie and am trying to get the hang of it. I have code to detect whether i get a username/password match, and now im trying to get the userid field so i can update the record. Heres what I have so far:
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
Using print_r($result) shows that there is an item, but im lost from here on out.

Try this.
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$userID= $row['username'] ;
// If you need other field as userID just change the sql and the index of $row according to that.
}
EDIT
If you want to get only one row.
if($result->num_rows==1)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
$userID = $row["username"];
}

Perhaps this will help. In any programming language, running an SQL query is going to consist of these steps:
Build the text of the SQL statement that you want to run.
(Optional) If your statement involves the use of parameters (or "placeholders"), prepare an array of the parameter-values that are to be substituted for each of them.
("Prepare" and...) "Run" the query, on some previously-opened "database connection." (In your example, "$link" must correspond to that connection.) This gives you a handle (you called it "$result") that corresponds to the zero-or-more rows that were returned by that query.
Now, use that handle to retrieve each of these rows, one at a time, until there are no more or until you're tired of doing it.
(Optional) Be neat and tidy and "close" the handle, thus indicating to the database system that it can discard all of the resources it was using to furnish those rows to you.
"Those, in simple terms, are the basic steps that every program in the known universe are going to go through," and if you now browse again through the PHP documentation, you'll see that there are functions that correspond to each of these steps. Browse through the chapters you've been reading and see if you can now match the up to the scenario I just described. HTH...

Related

INSERT INTO not working for 2nd table

I'm new to PHP but normally able to solve most problems but this one has got me.
I'm trying to create a newsletter sign up (single field) with a single submit button. I have this working fine, sending out an email and inserting the form data into my table. However I want to add functionality to have a confirmation email send to the person who signs up. I've done extensive research and I know the method behind this but my code just is not inputting data into my 2nd table used to store the confirmation information.
I have 2 tables:
Table 1 named 'newsletter' columns are:
idmail,emailaddress,datetime,state
idmail is set to AUTO_INCREMENT
Table 2 named 'confirm' columns are:
idconfirm,emailaddress,confirmkey
Here is my code (I've omitted the email part which goes after this as that all work OK):
//connect to database
include('admin/connection.php');
$email = mysqli_real_escape_string($dbc, $_POST['email']);
//check if value exists in table
$result = mysqli_query($dbc, "SELECT emailaddress FROM newsletter WHERE emailaddress = '$email'");
if (mysqli_num_rows($result)==0) {
//Insert value into database
$query1 = mysqli_query($dbc, "INSERT INTO newsletter(emailaddress, datetime, state) VALUES('$email','$now','0')");
mysqli_query($dbc, $query1);
// Get ID of last record
$id = mysqli_insert_id($dbc);
//Create a random key
$hash = $email.date('mY');
$hash = md5($hash);
//Insert value into database
$query2 = mysqli_query($dbc, "INSERT INTO confrim(idconfirm, emailaddress, confirmkey) VALUES('$id','$email','$hash')");
mysqli_query($dbc, $query2);
When I submit an email address, the first table is populated correctly.
The goal here is to get the auto ID created in the first INSERT INTO query into a variable then to add that in the 2nd tables column named 'idconfim'.
I tried:
echo $id;
echo $email;
echo $hash;
and all of the variables hold the correct information.
Does anyone have any ideas?
I've tried to many things to list here, but I've researched this and I just don't know where I'm going wrong.
Thanks in advance.
I'm posting my comment as an answer here:
The problem here is this $query2 = mysqli_query($dbc,... '$hash')"); mysqli_query($dbc, $query2); and you should have gotten an error about that. This besides the possible typo for the table name confrim.
You need to remove mysqli_query($dbc, $query2); here and replace it with:
if($query2){ echo "Success"; }
else{ echo "Error: " . mysqli_error($dbc);
(Another edit): You did the same error here:
$query1 = mysqli_query($dbc, "INSERT INTO newsletter ... '$now','0')");
mysqli_query($dbc, $query1);
and needs to be changed to:
if($query1){ echo "Success"; }
else{ echo "Error: " . mysqli_error($dbc);
As stated in comments by RiggsFolly; don't use MD5 to hash passwords, it's no longer safe. A lot of water's run under the bridge in over 30 years.
Use password_hash() http://php.net/manual/en/function.password-hash.php and a prepared statement.
Edit: It looks to me now that after looking at your code again, that you're not trying to save a password, but more as a confirmation key. If that is the case, then you can disregard the password stuff. However, if you do decide to use MD5 to store passwords with in the future, don't.
One of the problems is that you aren't showing the MySQL error, if there is one. So you need to either check the server logs for the error in PHP, you can force to print the error to the error log or do something else:
for example:
mysqli_query($dbc, $query2) or error_log(mysqli_error($dbc));
mysqli_query($dbc, $query2) or custome_error_handler(mysqli_error($dbc));
As well php should be returning an HTTP error to the client. You should be catching that error.
Once you see the SQL error it will be easy to figure out what you did wrong.
EDIT Fred ii caught the real error, but I think the error would have been thrown the first time the mistake is made:
mysqli_query($dbc, $query1);
$query1 isn't a string. And if you noticed you already executed the query on the line above. Reading the PHP error logs will show you exactly where the error is.
Sorry for wasting time.
Thanks to jeffery_the_wind for pointing me to the logs. I will use them in future.
The problem was TWO spelling mistakes, one in the column name in the php and one on the mysql database. confrim is not a word! I'm slightly lexdixlick!
Thanks for your prompt responses.

multi query select using wrong array?

I have a multi query select which half works. The first query is straight forward.
$sql = "SELECT riskAudDate, riskClientId, RiskNewId FROM tblriskregister ORDER BY riskId DESC LIMIT 1;";
The second one doesn't seem to work even when I do it on its own:
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
If I get rid of the LAST it returns the first entry in that field of the table. I want to use the LAST to get the LAST entry in that field.
When I do the first query on its own I get the data returned and I can echo it to the screen. When I add the second (with out the LAST) I get nothing. Here is what I am using
$result = $conn->query($sql);
if ($result == TRUE){
$r = $result->fetch_array(MYSQLI_ASSOC);
echo $r['riskAudDate'];
echo $r['riskClientId'];
echo $r['RiskNewId'];
echo $r['riskFacility'];
echo "<pre>";
print_r($r);
echo "</pre>";
}
The last bit is just for me to see whats in the array and just for testing.
So I have worked out that its the results array that is not right.
If I change the actual query to multi query I get this:
Call to a member function fetch_array() on boolean
So the array bit seems to be wrong for a multi query. The data returned is one row from each table. It works for the top query but add in the second (which I'm not sure is correct anyway) and the whole things crashes. So I guess it's a two part question. Whats wrong with my inserts and whats wrong with my returned array?
There is no last() function in mysql, it is only supported in ms access, if I'm not much mistaken. In mysql you can do what you do in the 1st query: do an order by and limit the results to 1.
According to the error message, the $conn->query($sql) returns a boolean value (probably true), therefore you cannot call $result->fetch_array(MYSQLI_ASSOC) on it. Since we have no idea what exactly you have in $sql variable, al I can say is that you need to debug your code to detrmine why $conn->query($sql) returns a boolean value.
Although it is not that clear from mysqli_query()'s documentation, but it only supports the execution of 1 query at a time. To execute multiple queries in one go, use mysqli_multi_query() (you can call this one in OO mode as well, see documentation). However, for security reasons I would rather call mysqli_query() twice separately. It is more difficult to execute a successful sql injection attack, if you cannot execute multiple queries.
It seems to me you are trying to do two SQL-queries at once.
That is not possible. Do a separate
$result = $conn->query($sql);
if ($result == TRUE){
while( $r = $result->fetch_array(MYSQLI_ASSOC)) {
...
}
}
for each SQL-query.
concerning :
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
since the last function does not exists in MySQL i would recommend doing a sort like this(because i don't know what you mean with last )
$sql ="SELECT riskFacility FROM tbleClients order by riskFacility desc limit 0,1";

How to print ONLY the data, as a string, from a mysql row

I have tried to simply print/echo the data from this row in my table:
I then use the following code (without all the connect stuff):
//please just ignore the query part
$sql2 = "SELECT Password FROM bruger WHERE Brugernavn='$Login_Navn'";
$result2 = mysqli_query($con, $sql2);
$row_result2 = mysqli_fetch_assoc($result2);
print_r($row_result2);
And the output of this ends out being:
I would like to know what i have to do to make it appear without all the "Array ([Password]....." stuff, so it just ends out being plain "TestPassword".
-Do i have to use another function?
Thanks in advance!
Sidenote: Im creating a login system for a school project. It ain´t advanced in any way, and the security/encryption etc. is as low as it gets. But that´s not really what im interested in with the project.
If you have some reading material on how to create a login system properly tho´ it would be appreciated.
That would be echo $row_result2['Password'];
You need to specify the corresponding index of the array to get the respective element to be printed.
You would echo the place in the array
echo($row_result2['Password']);
If your query brings back multipule fields you could loop over them:
foreach($row_result2 as $key => $val)
{
echo($key . ':' . $value);
}
Lastly, instead of storing into a associated array, you could use mysqli's bind to bind the results to single varibles:
$sql2 = 'SELECT Password FROM bruger WHERE Brugernavn=?';
$stmnt = mysqli_prepare($con, $sql2);
mysqli_stmnt_bind_param($stmnt,'s',$Lpgin_Navn);
mysqli_stmnt_bind_result($stmnt,$result2);
mysqli_stmnt_execute($stmnt);
mysqli_stmnt_fetch($stmnt);
echo($result2);
Or object oriented:
$sql2 = 'SELECT Password FROM bruger WHERE Brugernavn=?';
$stmnt = $con->prepare($sql2);
$stmnt->bind_param('s',$Lpgin_Navn);
$stmnt->bind_result($result2);
$stmnt->execute();
$stmnt->fetch();
echo($result2);
The use of mysqli_prepare protects your database from SQL injection attacks (consier if $Login_Navn = "'; drop table burger; --"). Binding the parameter tells it which string to sanitize when running the query. It also will speed up the time it takes to run the same query multiple times on different passed strings.
Lastly, never store passwords if you can help it. If you must, you should read the best practices for storing passwords. This, currently, includes salting (with random salt) and hashing (using a hash algo that is not currently known to be broken) the password before storing it in the database.

select from session username

I've read all the questions or at least lots of them and what I see is lots of code that for a beginner like me doesn't help a lot...
Probably, you will say that I'm a noob to start making my own webpage with login, register, and all that stuff and I also see people talking about giving up on mysql stuff to avoid sql injection and all of those security details.
All I need to know is a simply a thing about 1 code I'm getting wrong.
$mail = mysql_query("select email from users where username = '".$_SESSION['username']."'");
This is the variavel I have made to get the email of the actual user in the logged in session.
When I put your email is <?php echo"$mail".; ?>, it gives me the next detail:
your email is Resource id #8.
Why am I getting that? I've made the variable in a place with session started but I don't get what I have in that column on the specified user.
Sorry if I shouldn't post that in here, but I really don't see anyone with the same problem. All I see is complex codes and I really don't understand a lot of that.
I'm still a beginner, so if you guys can give me an hand, I will be grateful.
You have to use mysql_fetch_[array|object|assoc] PHP function
$res = mysql_query("select email from users where username = '".$_SESSION['username']."'");
$field = mysql_fetch_assoc($res);
echo $field['email'];
You have to fetch the returning rows of your query:
$row = mysql_fetch_assoc($query/$mail);
All the columns you queried will be in the array $row now.
print "Email: " . $row['email'];
This example assumes the query only returned one row.
If you were to query for several rows, you have to call mysql_fetch_assoc each time you wanted a new row:
while($row = mysql_fetch_assoc($query)) {
Good luck.
Take what you need.
$user = strip_tags($_SESSION['username']);
$sql = sprintf("SELECT FROM email WHERE username='%s'", mysql_real_escape_string($user));
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$mail = $row['email'];
echo "Your email is" .$mail;
The strip_tags() method will remove any HTML tags in the submitted entry.
I like to use the sprintf() method when making single row queries because it's a lot faster to just paste and change attribute names then worry about using the correct quote syntax.
Once your query is process you need to fetch the results then you can access the data inside the tables.
I hope this helps you out.

MySQL - PHP Column Sum

I have searched all over the internet and have found various "helpful" tips about how to do a column sum with PHP and a MySQL table. The problem is that I can not get ANY of them to work.
Essentially I have a very simple database with 2 users. The table within the database is called users and each entry has a 'Name' and a 'Total Steps'. All I want to do is display the result of the total steps of each user and then a sum of their steps.
Here is my code:
<?php
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
$row = mysql_fetch_assoc($steps);
$sum = $row['value_sum'];
?>
However, I get this error upon loading the page:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /nfs/nfs4/home/msnether/apache/htdocs/st.php
Since I don't know PHP or MySQL very well yet, this is quite frustrating and I would appreciate any help.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST
$conn = mysql_connect('database_server','database_username','database_password');
SECOND : Execute a database connection.
mysql_select_db($conn,'database name');
THIRD : Create a Query(you may insert your query here)..
$sql= mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = mysql_fetch_array($sql)){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
If you "Do not know PHP and Mysql well" then, knowing or die(mysql_error()) will be a pretty useful tool for you in the future. Just add it here, and see what mysql will make you understand politely.
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users") or die(mysql_error());

Categories