简体   繁体   中英

PHP/mysql fetch multiple variables in array

I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:

$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);

And my result is this. 在此处输入图片说明

First of all, combine your queries into one:

$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);

In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.

When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:

$row['user_name'] or $row['server'] etc..

Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.

You should use pdo or mysqli and here is your code;

  $user_id = &$_POST["user_id"];
    if($user_id){
        $result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
        /*You should use single quotes for escaping sql injection*/
        if($result){
            $vars = mysql_fetch_array($result);
            if($vars){
                list($username,$server,$link,$lpoints) = $vars;
            }
            else{
                //do something with errors
            }
            mysql_free_result($result);
        }
        else{
            //do something with errors
        }
    }
    else{
        //do something with errors
    }

Try This-

$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);

Now you got what you wanted based on your requirement use the data to insert or update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM